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.
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.
Yes, old objects are destroyed after they are copied to the new buffer.
Use a for loop and reference pointer To iterate through the vector, run a for loop from i = 0 to i = vec. size() .
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.
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);
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