给定位置,如何获取列表中的某个元素?

2022-01-07 00:00:00 list c++ stl

所以我有一个列表:

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

我不确定,但我相信这将是数组中的第 0"个元素.有什么我可以使用的函数可以返回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::vectorstd::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::liststd::advance在迭代器上调用operator++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.

相关文章