如果传递一个空范围,vector::erase() return 的迭代器会做什么?
What iterator does vector::erase() return if passed an empty range?
根据cppreference.com and cplusplus.com,函数std::erase(first, last)
returns "an iterator following the last removed element".
但是,在完全没有移除元素的特殊情况下,即first == last
(空范围)时,return值是什么还不清楚。截至 2020 年 1 月 19 日,上述来源中 none 提到了这种特殊情况。
例如,在下面的代码中:
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 by q2
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()
。
#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.
根据cppreference.com and cplusplus.com,函数std::erase(first, last)
returns "an iterator following the last removed element".
但是,在完全没有移除元素的特殊情况下,即first == last
(空范围)时,return值是什么还不清楚。截至 2020 年 1 月 19 日,上述来源中 none 提到了这种特殊情况。
例如,在下面的代码中:
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()
。
#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.