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 Answers
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.
Comments
std::vector<int> a = {1,2,3,4,5};
works as of C++11.
See: http://en.cppreference.com/w/cpp/language/list_initialization
std::vector<int> x = { 1, 2, 3 };works just fine for me. Get a newer compiler.