1

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.

Joseph
  • 1,458
  • 15
  • 20
  • You mean "contiguous"? `std::vector` is designed to hold contiguous elements, how would it not? – aslg Mar 31 '16 at 10:18

2 Answers2

6

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
   }
}
bashrc
  • 4,725
  • 1
  • 22
  • 49
5

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.

  • But if you are aware of the possible memory framentation you should write your own memory allocator [link](http://www.gamedev.net/page/resources/_/technical/general-programming/c-custom-memory-allocation-r3010) – Asier Sánchez Rodríguez Mar 31 '16 at 10:23
  • 3
    How could swapping two vector elements possibly cause fragmentation? – molbdnilo Mar 31 '16 at 10:25
  • I was not talking about that swapping two vector produce memory framentation, I was talking about that I you care about the memory of your program it is interesting to create your own memory pool – Asier Sánchez Rodríguez Mar 31 '16 at 10:28
  • 1
    Yes, but that's as relevant to the question (and answer) as the fact that if you want sweet tea you can put sugar in it. – molbdnilo Mar 31 '16 at 10:38