向量排序会使迭代器无效吗?
std::vector<string> names;
std::vector<string>::iterator start = names.begin();
std::vector<string>::iterator end = names.end();
sort (start,end);
//are my start and end valid at this point?
//or they do not point to front and tail resp?
std::vector<string> names;
std::vector<string>::iterator start = names.begin();
std::vector<string>::iterator end = names.end();
sort (start,end);
//are my start and end valid at this point?
//or they do not point to front and tail resp?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
根据 C++ 标准 §23.1/11:
§25.3“排序和相关操作”没有指定迭代器将无效,因此问题中的迭代器应该保持有效。
According to the C++ Standard §23.1/11:
§25.3 "Sorting and related operations" doesn't specify that iterators will be invalidated, so iterators in the question should stay valid.
它们仍然指向开始和结束。向量的这些槽中的值可能已更改,但每个槽所在的存储位置保持不变。
They still point to the beginning and end. The values in those slots of the vector have probably changed, but the storage location in which each resides remains the same.
std::sort
不会使向量的迭代器无效。排序模板在迭代器上使用*
运算符来访问和修改向量的内容,并且通过迭代器修改向量元素到向量中已有的元素不会使任何迭代器无效。总之,
除了对 Kirill V. Lyadvinsky 提供的标准的支持 (向量排序是否会使迭代器无效?):
std::sort
will not invalidate iterators to a vector. The sort template uses the*
operator on the iterators to access and modify the contents of the vector, and modifying a vector element though an iterator to an element already in the vector will not invalidate any iterators.In summary,
In addition to the support for the standard provided by Kirill V. Lyadvinsky (Does a vector sort invalidate iterators?):
std::vector
将其元素保存在连续的内存中。std::sort
按值获取参数(迭代器)并重新排列它们之间的顺序。最终结果是局部变量start
和end
仍然指向向量的第一个和最后一个元素。std::vector
keeps its elements in contiguous memory.std::sort
takes arguments (iterators) by value and re-arranges the sequence between them. The net result is your local variablesstart
andend
are still pointing to first and one-past-the-last elements of the vector.