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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With