How to get a certain element in a list, given the position?(给定位置,如何获取列表中的某个元素?)
问题描述
所以我有一个列表:
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::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在迭代器上调用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.
这篇关于给定位置,如何获取列表中的某个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:给定位置,如何获取列表中的某个元素?
基础教程推荐
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- c++ STL设置差异 2022-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
