从集合中的任意索引获取元素 [英] Get element from arbitrary index in set

查看:64
本文介绍了从集合中的任意索引获取元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组类型为 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆