Could anybody explain to me why we can initialize a vector this way?
int a[]={1,2,3,4,5}; std::vector<int> vec(a,a+sizeof(a)/sizeof(int));
I also know this way std::vector<int> vec(5,0);
meaning vec has five elements and they are all initialized as 0. But these two ways are not related. How to explain the first one. What is the best way (what most people use) to initialize a vector if we know the values.
Asked
Active
Viewed 390 times
2

Vlad from Moscow
- 301,070
- 26
- 186
- 335

daydayup
- 2,049
- 5
- 22
- 47
-
`std::vector
x = { 1, 2, 3 };` works just fine for me. Get a newer compiler. – Captain Obvlious Jul 10 '15 at 21:05 -
possible duplicate of [What is the easiest way to initialize a std::vector with hardcoded elements?](http://stackoverflow.com/questions/2236197/what-is-the-easiest-way-to-initialize-a-stdvector-with-hardcoded-elements) – Captain Obvlious Jul 10 '15 at 21:06
-
Thank you. it looks like only c++11 or newer supports that way – daydayup Jul 10 '15 at 21:10
3 Answers
7
Class std::vector has constructor that accepts a pair of input iterators
template <class InputIterator>
vector(InputIterator first, InputIterator last, const Allocator& = Allocator());
And this declaration
std::vector<int> vec(a,a+sizeof(a)/sizeof(int));
includes a call of the constructor where a
and a + sizeof(a)/sizeof(int)
are two random access iterators because pointers have such category of iterators.
Here a
and a + sizeof(a)/sizeof(int)
are two pointers that specify a range of initializers taken from the array for the created object of type std::vector<int>
.
Take into account that you could also use the constructor that accepts an initializer list. For example
std::vector<int> v { 1, 2, 3, 4, 5 };
This constructor is supported starting from the C++ 2011.

Vlad from Moscow
- 301,070
- 26
- 186
- 335
0
Also you can use:
int a[5]={1,2,3,4,5};
std::vector<int> vec;
for(int i=0; i<5: i++) vec.push_back(a[i]);

Alexander Leon VI
- 499
- 1
- 4
- 18
0
std::vector<int> a = {1,2,3,4,5};
works as of C++11.
See: http://en.cppreference.com/w/cpp/language/list_initialization

dan-O
- 354
- 1
- 10