从集合中的任意索引获取元素 [英] Get element from arbitrary index in set
问题描述
我有一组类型为 set< int>
的类型,我想让一个迭代器到达一个不是开始的地方.
I have a set of type set<int>
and I want to get an iterator to someplace that is not the beginning.
我正在执行以下操作:
set<int>::iterator it = myset.begin() + 5;
我很好奇为什么这样做不起作用,以及将迭代器添加到我想要的位置的正确方法是什么.
I am curious why this is not working and what is the correct way to get an iterator to where I want it.
推荐答案
myset.begin()+ 5;
仅适用于随机访问迭代器,该迭代器来自 std :: set
不是.
myset.begin() + 5;
only works for random access iterators, which the iterators from std::set
are not.
对于输入迭代器,有功能 std :: advance
:
For input iterators, there's the function std::advance
:
set<int>::iterator it = myset.begin();
std::advance(it, 5); // now it is advanced by five
在C ++ 11中,还有 std :: next
,这很相似,但不会更改其参数:
In C++11, there's also std::next
which is similar but doesn't change its argument:
auto it = std::next(myset.begin(), 5);
std :: next
需要一个正向迭代器.但是由于 std :: set< int> :: iterator
是双向迭代器,因此 advance
和 next
都可以使用.
std::next
requires a forward iterator. But since std::set<int>::iterator
is a bidirectional iterator, both advance
and next
will work.
这篇关于从集合中的任意索引获取元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!