Writing the contents of an int array to a vector

I want to write the contents of an array to a vector.

int A[]={10,20,30,40,50,60,70,80,90}; vector<int> my_vector; 

I used to copy the contents of array A to another array B using memcpy. I want to use my_vector instead of array B

How to write the contents of array A to my_vector in one shot without a for loop?

+4
source share
3 answers

You can use memcpy or use such initialization in C ++ 98/03.

 int A[]={10,20,30,40,50,60,70,80,90}; vector<int> my_vector(A, A + sizeof(A) / sizeof(*A)); 

You can also use an algorithm such as copy .

 std::copy(A, A + sizeof(A) / sizeof(*A), std::back_inserter(my_vector)); 

In C ++ 11, use std::begin(A) , std::end(A) to start and end the array.

+3
source

With C ++ 2011 you want to use

 std::copy(std::begin(A), std::end(A), std::back_inserter(my_vector)); 

... or

 std::vector<int> my_vector(std::begin(A), std::end(A)); 

... or, in fact:

 std::vector<int> my_vector({ 10, 20, 30, 40, 50, 60, 70, 80, 90 }); 

If you do not have C ++ 2011, you want to define

 namespace whatever { template <typename T, int Size> T* begin(T (&array)[Size]) { return array; } template <typename T, int Size> T* end(T (&array)[Size]) { return array + Size; } } 

and use whatever::begin() and whatever::end() along with one of the first two approaches.

+6
source
 #include <algorithm> #include <vector> int main() { int A[]={10,20,30,40,50,60,70,80,90}; std::vector<int> my_vector; unsigned size = sizeof(A)/sizeof(int); std::copy(&A[0],&A[size],std::back_inserter(my_vector)); } 

C ++ 11 is much simpler.

 #include <vector> #include <algorithm> int main() { int A[]={10,20,30,40,50,60,70,80,90}; std::vector<int> my_vector(std::begin(A),std::end(A)); } 
+4
source

Source: https://habr.com/ru/post/1431996/


All Articles