[英]Does std::unique invalidate vector iterators?
For this code: 对于此代码:
std::vector<int> v = {...};
std::sort(v.begin(), v.end());
// Does this work?
std::size_t unique_count = std::unique(v.begin(), v.end()) - v.cbegin();
In the last line, I think since std::unique
just moves stuffs around inside the vector and does not insert anything into it, no iterators should be invalidated, and so the way I'm calculating unique_count
should be correct. 在最后一行中,我认为自std::unique
以来,只是在Vector内部移动了东西,并且没有在其中插入任何东西,没有迭代器应该被使无效,因此我计算unique_count
的方式应该是正确的。 But I want to make sure that is the case. 但我想确保确实如此。 Is it? 是吗?
std::unique
is an algorithm. std::unique
是一种算法。 All stl algorithms operate on ranges, not containers. 所有stl算法都在范围上而不是容器上运行。
Although the algorithm may swap element contents, the iterators to those elements remain unchanged. 尽管该算法可以交换元素内容,但这些元素的迭代器保持不变。
This is a guarantee. 这是保证。
If it were not, then this could not work: 如果不是,那么这将不起作用:
#include <algorithm>
#include <vector>
#include <iostream>
#include <array>
int main()
{
auto unique_size = [](auto&& container)
{
std::sort(std::begin(container), std::end(container));
return std::unique(std::begin(container), std::end(container)) - std::cbegin(container);
};
std::cout << unique_size(std::vector<int> {6,5,4,4,3,2,1}) << std::endl;
std::cout << unique_size(std::array<int,7> {6,5,4,4,3,2,1}) << std::endl;
int x[] = {6,5,4,4,3,2,1};
std::cout << unique_size(x) << std::endl;
// Does this work? yes.
}
mandated output: 法定产出:
6
6
6
std::unique
return an iterator to one position past the last 'unique' element in the container. std::unique
将迭代器返回到容器中最后一个“ unique”元素之后的某个位置。
auto last = std::unique(v.begin(), v.end());
Then the range [ last
, v.end()
) contains whatever, you can't rely on v.cbegin()
. 然后范围[ last
, v.end()
)包含任何内容,您不能依赖v.cbegin()
。 Instead: 代替:
auto unique_count = std::distance(v.begin(), last);
will do the trick. 会成功的
http://en.cppreference.com/w/cpp/algorithm/unique http://en.cppreference.com/w/cpp/algorithm/unique
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.