Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 vector constructor copy vs range?

I can't understand the advantages of or differences between vector copy constructors and range constructors. When I construct three vectors like this:

    vector<int> FirstVec(3, 911); //fill constructor
    vector<int> SecondVec(FirstVec.begin(), FirstVec.end()); //range constructor
    vector<int> ThirdVec(FirstVec); //copy constructor

The contents of SecondVec and ThirdVec are exactly the same. Are there any scenarios in which using one of them has advantages? Thank you.

like image 476
moonwalker Avatar asked May 08 '15 10:05

moonwalker


People also ask

What happens if you use the default copy constructor for vector?

The default copy constructor will copy all members – i.e. call their respective copy constructors. So yes, a std::vector (being nothing special as far as C++ is concerned) will be duly copied.

Does vector copy constructor?

Yes, old objects are destroyed after they are copied to the new buffer.

Which of these are valid ways of iterating over this vector and printing its contents?

Use a for loop and reference pointer To iterate through the vector, run a for loop from i = 0 to i = vec. size() .

What is vector in C++ with example?

Vectors in C++ are sequence containers representing arrays that can change their size during runtime. They use contiguous storage locations for their elements just as efficiently as in arrays, which means that their elements can also be accessed using offsets on regular pointers to its elements.


1 Answers

The range constructor is quite useful when you want to copy the items of a different type of container, or don't want to copy a full range. For example

int a[] = {1,2,3,4,5};
std::set<int> s{3, 911};
std::vector<int> v0{1,2,3,4,5};

std::vector<int> v1(std::begin(a), std::end(a));
std::vector<int> v2(a+1, a+3);
std::vector<int> v3(s.begin(), s.end());
vector<int> v4(v0.begin(), v0.begin() + 3);
like image 145
juanchopanza Avatar answered Oct 02 '22 19:10

juanchopanza