本网站暗示清除向量可能会改变容量:
http://en.cppreference.com/w/cpp/container/vector/clear
许多实现在调用clear()之后不会释放已分配的内存,从而有效地保持向量的容量()不变.
但根据@JamesKanze的说法,这是错误的,标准要求明确不会改变容量.
标准说什么?
我实例化了一个std::vector foo(1000)
.
foo.size()
现在是1000,foo.capacity()
也是1000.
如果我清除矢量foo.clear()
,size()
现在是0,但是什么是capacity()
?标准是否对此有所说明?
回答如何自我复制载体?让我对迭代器失效有点困惑.一些文献说"如果使用insert,push_back等,则认为所有迭代器都无效".多数民众赞成,它可能会导致向量增长,从而使迭代器无效.那个我知道会有足够空间的特殊情况怎么样?
第一次尝试:
myvec.reserve(myvec.size()*3); //does this protect me from iterator invalidation?
vector<string>::iterator it = myvec.end();
myvec.insert(myvec.end(), myvec.begin(), it);
myvec.insert(myvec.end(), myvec.begin(), it);
Run Code Online (Sandbox Code Playgroud)
经过一些优秀的答案第二次尝试
auto size = myvec.size();
myvec.reserve(size*3); //does this protect me from iterator invalidation?
myvec.insert(myvec.end(), myvec.begin(), myvec.begin()+size);
myvec.insert(myvec.end(), myvec.begin(), myvec.begin()+size);
Run Code Online (Sandbox Code Playgroud)
经过更优秀的答案第三次尝试:
auto size = myvec.size();
myvec.reserve(size*3); //does this protect me from iterator invalidation?
back_insert_iterator< vector<string> > back_it (myvec);
copy (myvec.begin(),myvec.begin()+size,back_it);
copy (myvec.begin(),myvec.begin()+size,back_it);
Run Code Online (Sandbox Code Playgroud)
Josuttis的"C++标准库参考"引用了这句话:
插入或删除元素会使引用,引用和迭代器无效,这些引用,引用和迭代器引用以下元素.如果插入导致重新分配,则会使所有引用,迭代器和指针无效.
表明我的代码是安全的和定义的行为.标准中是否有一个保证这一点的段落?