Will vectors stay contiguous after swapping two elements?
PS: Regardless of the answer what might be, How can we really be sure? if that's possible.
Will vectors stay contiguous after swapping two elements?
PS: Regardless of the answer what might be, How can we really be sure? if that's possible.
How can we really be sure?
For most people the guarantee from the standard should be sufficient.
[n3337, 23.6.6.1] The elements of a vector are stored contiguously, meaning that if v is a vector where T is some type other than bool, then it obeys the identity &v[n] == &v[0] + n for all 0 <= n < v.size().
You can do this is in a hacky way.
template<typename T>
void PrintVectorElements(vector<T> C){
auto startPtr = C.data();
for (auto x = C.begin(); x != C.end(); ++startPtr, ++x){
assert(*startPtr == *x);
assert(&(*x) == startPtr); // take this line with a pinch of salt
}
}
Swapping two elements just copies the data from one to the other and viceversa, the memory allocated remains the same, so, yes, it remains contiguous.