c++之如果传递空范围,vector::erase() 返回什么迭代器
根据 cppreference.com和 cplusplus.com ,函数std::erase(first, last)
返回“最后一个删除元素之后的迭代器”。
但是,在完全没有被移除元素的特殊情况下,即first == last
时,返回值是什么不清楚。 (空范围)。截至 2020 年 1 月 19 日,上述消息来源均未提及此特殊情况。
例如,在以下代码中:
std::vector<int> v{1, 2, 3, 4};
auto it1 = v.erase(v.begin(), v.begin());
auto it2 = v.erase(v.end(), v.end());
it1
的值是多少和
it2
?
请您参考如下方法:
这是在 [sequence.reqmts] 中指定的:
The iterator returned by
a.erase(q1, q2)
points to the element pointed to byq2
prior to any elements being erased. If no such element exists,a.end()
is returned.
(注意:我链接了 C++17 最终工作草案,但这种措辞至少从 C++98 开始就存在,请参阅@Peter 的评论)
所以我们应该有
it1 == v.begin()
和
it2 == v.end()
.
Live test :
#include <iostream>
#include <vector>
int main()
{
std::vector<int> v{1, 2, 3, 4};
auto it1 = v.erase(v.begin(), v.begin());
auto it2 = v.erase(v.end(), v.end());
std::cout << std::distance(v.begin(), it1) << std::endl;
std::cout << std::distance(v.begin(), it2) << std::endl;
}
输出:
0
4
为了澄清这种行为,我更新了 cppreference文档,现在是:
iterator erase( const_iterator pos ); iterator erase( const_iterator first, const_iterator last );
Return Value
Iterator following the last removed element.
If pos refers to the last element, then the end() iterator is returned.
If last==end() prior to removal, then the updated end() iterator is returned.
If [first, last) is an empty range, then last is returned.
1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。