交换后,矢量会保持连续吗?

时间:2016-03-31 10:16:40

标签: c++ c++11 vector swap contiguous

交换两个元素后,矢量会保持连续吗?

PS:无论答案是什么,我们怎么能确定?如果可能的话。

2 个答案:

答案 0 :(得分:6)

  

我们怎么能确定?

对于大多数人来说,标准的保证应该足够了。

  

[n3337,23.6.6.1]向量的元素是连续存储的,这意味着如果v是   一个向量,其中T是某种类型而不是bool,然后它   对于所有0< = n< 0< = n< n< = n< n< v.size()。

你可以用黑客的方式做到这一点。

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
   }
}

答案 1 :(得分:5)

交换两个元素只是将数据从一个复制到另一个,反之,分配的内存保持不变,所以,是的,它仍然是连续的。

相关问题