Can I do vector.insert( vector.end(), vector.cbegin(), vector.cend() ) ?
-
I want to duplicate content of std::vector.
I thought about possible realisations of std::vector::insert(), and all of them should crash in case of iterators aliasing mentioned in the caption. But I have not found any mentions of aliasing in descriptions of the function. Any ideas? will it crash? What is the best, C++ way of duplicate vector content?
-
First: There is no function cbegin() or cend() in vector<> only different overloads for begin()/end().
Second: While inserting the new elements, the vector might reallocate its memory and therefore invalidate all iterators referencing its context (inclusive the ones you used as source).
Third: One solution would be, doubling the size of the vector via resize() and using std::copy to fill its second half. Another idea ist to push_back() the elements one by one (using operator[] to get the source values).
-
Hmm. In Visual studio I always used cbegin() / cend() to get const iterator even of non-const vector. I use this to not accidentally modify vector data.
Ok, I see:
std::vector<T> v; ... v.resize(v.size() * 2); std::vector<T>::iterator const middle(v.begin() + v.size() / 2); std::copy(v.begin(), middle, middle); for(std::vector<T>::iterator i(middle); i != v.end(); ++i) i->someAdditionalProcessing();
Thank you.
But... I just read that std::vector::reserve() guarantees that no reallocation will take place. So, may it will be better to do this:
v.reserve(v.size() * 2); v.insert( v.end(), v.begin(), v.end() ); for(std::vector<T>::iterator i(v.begin() + v.size() / 2); i != v.end(); ++i) i->someAdditionalProcessing();
-
First: There is no function cbegin() or cend() in vector<> only different overloads for begin()/end().
There is.. at least in the current implementation which comes with VS2010 - i guess it is a C++11 feature.
-
Dieser Thread wurde von Moderator/in Jochen Kalmbach aus dem Forum C++/CLI mit .NET in das Forum Compiler- und IDE-Forum verschoben.
Im Zweifelsfall bitte auch folgende Hinweise beachten:
C/C++ Forum :: FAQ - Sonstiges :: Wohin mit meiner Frage?Dieses Posting wurde automatisch erzeugt.