为什么无法向关联容器的迭代器添加数字?
我有一个 std::set 并且我想迭代集合中的元素对,所以我编写了 2 个 for 循环,如下所示:
for(std::set<T>::iterator i=mySet.begin();i!=mySet.end();++i)
{
for(std::set<T>::iterator j=i+1;j!=mySet.end();++j)
{
// do something
}
}
编译器告诉我不能向迭代器添加数字。但是我可以增加和减少它们。我发现我可以跳过第一次迭代的解决方法:
for(std::set<T>::iterator i=mySet.begin();i!=mySet.end();++i)
{
std::set<T>::iterator j=i;
for(++j;j!=mySet.end();++j)
{
// do something
}
}
为什么我不能只添加一个数字,为什么我必须递增?
I have an std::set and I wanted to iterate trough the element pairs in the set so I wrote 2 for loops like this:
for(std::set<T>::iterator i=mySet.begin();i!=mySet.end();++i)
{
for(std::set<T>::iterator j=i+1;j!=mySet.end();++j)
{
// do something
}
}
The compiler told me that I can't add numbers to iterator. However I can increment and decrement them. A workaround I find that I can skip the first iteration:
for(std::set<T>::iterator i=mySet.begin();i!=mySet.end();++i)
{
std::set<T>::iterator j=i;
for(++j;j!=mySet.end();++j)
{
// do something
}
}
Why I can't just add a number why I have to increment?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您只能使用随机访问迭代器来执行此操作,因此原因与容器上没有索引操作符时速度缓慢的原因相同。另请参阅 为什么 std:: 没有运算符[]列表?
you can do this only with random access iterator, so the reasons are the same as for not having an indexoperator on containers when it would be slow. See also Why isn't there an operator[] for a std::list?
和往常一样,Boost有一个解决方案:
当然你也可以考虑
As usual, Boost has a solution:
Of course you could also consider
因为set只支持双向迭代器,所以只允许递增和递减。
集合通常是树结构,因此这些是唯一有意义的操作。
Because set only supports bidirectional iterator, that only allows increments and decrements.
Set is usually a tree structure therefore these are the only operations that make sense.
请查看此处迭代器的定义。您正在寻找的方法仅为容器的迭代器定义,该迭代器允许随机访问而集合不支持。
Look here at the definition of iterators. The method which you are looking for is defined only for iterators of containers which allows random access which set doesn't support.
您的问题已经得到解答,但请注意,您可以像这样缩短代码:
Your question was already answered, but note that you can shorten your code like this: