Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing contents of a int array into a vector

Tags:

c++

stl

vector

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

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

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

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

like image 487
ajay bidari Avatar asked Dec 12 '22 22:12

ajay bidari


1 Answers

Using 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, actually:

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

If you don't 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() together with one of the first two approaches.

like image 84
Dietmar Kühl Avatar answered Dec 26 '22 04:12

Dietmar Kühl