Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the simplest way to convert array to vector?

Tags:

c++

arrays

vector

What is the simplest way to convert array to vector?

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

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

like image 746
Amir Saniyan Avatar asked Jan 08 '12 12:01

Amir Saniyan


People also ask

How do you turn an array into a vector?

To convert an array to vector, you can use the constructor of Vector, or use a looping statement to add each element of array to vector using push_back() function.


1 Answers

Use the vector constructor that takes two iterators, note that pointers are valid iterators, and use the 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; it's the generic way of getting the number of elements in an array. Note that x + sizeof x / sizeof x[0] points one element beyond the last element.

like image 160
Fred Foo Avatar answered Sep 25 '22 16:09

Fred Foo