What is the easiest way to convert an array to a vector?

What is the easiest way to convert an array to a vector?

void test(vector<int> _array) { ... } int x[3]={1, 2, 3}; test(x); // Syntax error. 

I want to convert x from an int array to a vector in the simplest way.

+80
c ++ arrays vector
Jan 08 2018-12-12T00:
source share
5 answers

Use the vector constructor, which takes two iterators, note that pointers are valid iterators and use implicit conversion from arrays to pointers:

 int x[3] = {1, 2, 3}; std::vector<int> v(x, x + sizeof x / sizeof x[0]); test(v); 

or

 test(std::vector<int>(x, x + sizeof x / sizeof x[0])); 

where sizeof x / sizeof x[0] is obviously 3 in this context; this is a common way to get the number of elements in an array. Note that x + sizeof x / sizeof x[0] indicates one item after the last item.

+126
Jan 08 2018-12-12T00:
source share

Personally, I really like the C ++ 2011 approach, because it does not require the use of sizeof() and I don’t remember setting the boundaries of the array if you ever change the boundaries of the array (and you can define the corresponding function in C ++ 2003, if you also want to):

 #include <iterator> #include <vector> int x[] = { 1, 2, 3, 4, 5 }; std::vector<int> v(std::begin(x), std::end(x)); 

Obviously, with C ++ 2011, you might want to use initializer lists:

 std::vector<int> v({ 1, 2, 3, 4, 5 }); 
+102
Jan 08 '12 at 3:50
source share

Pointers can be used like any other iterators:

 int x[3] = {1, 2, 3}; std::vector<int> v(x, x + 3); test(v) 
+13
Jan 08 2018-12-12T00:
source share

Here you are asking the wrong question - instead of putting everything into a vector, ask how you can convert the test to work with iterators instead of a specific container. You can also provide congestion to maintain compatibility (and at the same time handle other containers for free):

 void test(const std::vector<int>& in) { // Iterate over vector and do whatever } 

becomes:

 template <typename Iterator> void test(Iterator begin, const Iterator end) { // Iterate over range and do whatever } template <typename Container> void test(const Container& in) { test(std::begin(in), std::end(in)); } 

What allows you to do:

 int x[3]={1, 2, 3}; test(x); // Now correct 

( Perfect demonstration )

+8
Oct 31 '14 at 23:21
source share

One simple way would be to use the assign() function, which is predefined in the vector class.

eg

 array[5]={1,2,3,4,5}; vector<int> v; v.assgin(array, array+5); // 5 is size of array. 
0
07 Sep '19 at 20:43
source share



All Articles