C++ 给定位置,如何获取列表中的某个元素?
所以我有一个清单:C++ 给定位置,如何获取列表中的某个元素?,c++,list,stl,C++,List,Stl,所以我有一个清单: list<Object> myList; myList.push_back(Object myObject); ?如果您经常需要访问序列的第n个元素,std::list,它被实现为双链接列表,可能不是正确的选择std::vector或std::deque可能更好 也就是说,您可以使用std::advance获得第n个元素的迭代器: std::list<Object> l; // add elements to list 'l'... unsigne
list<Object> myList;
myList.push_back(Object myObject);
?如果您经常需要访问序列的第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::next
有效地包装了对std::advance
的调用,使迭代器N
更容易前进,代码行更少,可变变量更少<在C++11中添加了code>std::next。std::list
不提供任何函数来获取给定索引的元素。您可以尝试通过编写一些代码来获得它,我不推荐这样做,因为如果您经常需要这样做,那么这将是低效的
您需要的是:std::vector
。将其用作:
std::vector<Object> objects;
objects.push_back(myObject);
Object const & x = objects[0]; //index isn't checked
Object const & y = objects.at(0); //index is checked
std::向量对象;
对象。向后推(myObject);
Object const&x=对象[0]//未检查索引
Object const&y=objects.at(0)//索引已检查
std::list l;
std::list::迭代器ptr;
int i;
对于(i=0,ptr=l.begin();i
也许不是最有效的方法。但是你可以把列表转换成向量
#include <list>
#include <vector>
list<Object> myList;
vector<Object> myVector(myList.begin(), myList.end());
您可以将其放在助手函数中:
#include <memory>
#include <vector>
#include <list>
template<class T>
shared_ptr<vector<T>>
ListToVector(list<T> List) {
shared_ptr<vector<T>> Vector {
new vector<string>(List.begin(), List.end()) }
return Vector;
}
效率不是很高,但如果必须使用列表,则可以遵从迭代器
*myList.begin()+N
没有数组,它是一个列表。如果您想按整数进行索引,为什么不使用vector
来代替呢?如果您总是想要元素0,请使用front()
。我还没有测试过这一点,但我假设myList.front()+num可以工作here@SergueiFedorov:不,当您因缺少随机访问而在搜索链接列表时支付性能惩罚时,如果需要在矢量或DEQE的中间插入或删除数据,则要付出更大的性能损失。这个问题实际上并没有包含足够的信息来决定他们是否在使用理想的容器。值得注意的是,当使用std::advance
或std::next
时,很容易调用UB。没有边界检查。
#include <list>
#include <vector>
list<Object> myList;
vector<Object> myVector(myList.begin(), myList.end());
auto x = MyVector[0];
#include <memory>
#include <vector>
#include <list>
template<class T>
shared_ptr<vector<T>>
ListToVector(list<T> List) {
shared_ptr<vector<T>> Vector {
new vector<string>(List.begin(), List.end()) }
return Vector;
}
auto MyVector = ListToVector(Object);
auto x = MyVector[0];
*myList.begin()+N