如何获取列表中的某个元素,给定位置? [英] How to get a certain element in a list, given the position?

查看:561
本文介绍了如何获取列表中的某个元素,给定位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个列表:

list<Object> myList;
myList.push_back(Object myObject);

我不确定,但我相信这将是数组。
是否有任何函数可以使用将返回myObject?

I'm not sure but I'm confident that this would be the "0th" element in the array. Is there any function I can use that will return "myObject"?

Object copy = myList.find_element(0);

推荐答案

如果你经常需要访问序列的第N个元素,那么作为双向链表实现的 std :: list 可能不是正确的选择。 std :: vector std :: deque 可能会更好。

If you frequently need to access the Nth element of a sequence, std::list, which is implemented as a doubly linked list, is probably not the right choice. std::vector or std::deque would likely be better.

也就是说,你可以使用 std :: advance 获得迭代器到第N个元素:

That said, you can get an iterator to the Nth element using std::advance:

std::list<Object> l;
// add elements to list 'l'...

unsigned N = /* index of the element you want to retrieve */;
if (l.size() > N)
{
    std::list<Object>::iterator it = l.begin();
    std::advance(it, N);
    // 'it' points to the element at index 'N'
}

对于不提供随机访问的容器,如 std :: list std :: advance 运算符++ 在迭代器 N 次。或者,如果您的标准库实现提供它,您可以调用 std :: next

For a container that doesn't provide random access, like std::list, std::advance calls operator++ on the iterator N times. Alternatively, if your Standard Library implementation provides it, you may call std::next:

if (l.size() > N)
{
    std::list<Object>::iterator it = std::next(l.begin(), N);
}

std :: next 有效地调用 std :: advance ,使得更容易推进迭代器 N 次的代码和较少的可变变量。 std :: next 已在C ++ 11中添加。

std::next is effectively wraps a call to std::advance, making it easier to advance an iterator N times with fewer lines of code and fewer mutable variables. std::next was added in C++11.

这篇关于如何获取列表中的某个元素,给定位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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