2

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.

3

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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]); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.