如何获得列表中的某个元素,给定位置?
所以,我已经有了一个名单:如何获得列表中的某个元素,给定位置?
list<Object> myList;
myList.push_back(Object myObject);
我不知道,但我相信,这将是在数组中的“零”的元素。 有没有我可以使用的函数返回“myObject”?
Object copy = myList.find_element(0);
?
如果您经常需要访问序列的第N个元素,则作为双向链表执行的std::list
可能不是正确的选择。 std::vector
或std::deque
可能会更好。
这就是说,你可以得到一个迭代器使用std::advance
的第N个元素:
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
:
if (l.size() > N)
{
std::list<Object>::iterator it = std::next(l.begin(), N);
}
std::next
有效地包装了一个调用std::advance
,使其更容易推进的迭代器N
倍更少的代码和更少的可变变量。在C++ 11中添加了std::next
。
由于缺乏随机访问而导致您在搜索链表时付出了性能损失,如果您需要在矢量或双端队列中插入或移除数据,则会付出更大的性能损失。这个问题实际上并没有包含足够的信息来决定他们是否将理想的容器用于他们的目的。 – tloach 2015-09-18 14:21:50
std::list
没有提供任何函数来获取给定索引的元素。您可以尝试通过编写一些我不推荐的代码来获得它,因为如果您经常需要这样做,效率会很低。
你需要的是:std::vector
。使用它作为:
std::vector<Object> objects;
objects.push_back(myObject);
Object obj = objects[0]; //get element given an index
std::list<Object> l;
std::list<Object>::iterator ptr;
int i;
for(i = 0 , ptr = l.begin() ; i < N && ptr != l.end() ; i++ , ptr++);
if(ptr == l.end()) {
// list too short
} else {
// 'ptr' points to N-th element of list
}
没有阵列 - 这是一个列表。如果你想用整数索引,为什么不用'vector'来代替? – 2011-04-20 16:52:32
如果您始终想要元素0,请使用'front()'。 – 2011-04-20 16:53:06
我没有测试过这个,但我会假设myList.front()+ num会在这里工作 – 2013-12-15 12:03:35