Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vectors - More Elegance?

Tags:

c++

vector

I am working with vectors and I am initialising them like so:

vector<int> values;

values.push_back(1);
values.push_back(2);
values.push_back(8);
values.push_back(12);
values.push_back(32);
values.push_back(43);
values.push_back(23);
values.push_back(234);
values.push_back(7);
values.push_back(1);

Is there a way, to push_back these elements in a way that is array-like? Like this:

    int numbers[2] = {1, 2};

The vector method takes up too many lines, IMO!

like image 495
Phorce Avatar asked Aug 12 '26 13:08

Phorce


1 Answers

In C++11 you can use brace initialization with any container.

std::vector <int> v = {1, 2, 8, 12, 32 ...};

In C++03 you can do this

const int arr[] = {1, 2, 8, 12, 32 ... };
const int size = sizeof arr / sizeof arr[0];
std::vector<int> v(arr, arr + size);

or use boost assign.

#include <boost/assign.hpp>
using namespace boost::assign;
///...
{
    std::vector<int> v;
    v += 1, 2, 8, 12, 32;
}
like image 160
Armen Tsirunyan Avatar answered Aug 15 '26 06:08

Armen Tsirunyan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!