C++ 如何从c++;列表
我有一个C++ 如何从c++;列表,c++,list,get,C++,List,Get,我有一个列表: list<Student>* l; list中是否有一个函数或方法使其能够执行此操作?std::list没有随机访问迭代器,因此必须从前面的迭代器开始执行4次。您可以手动执行此操作,也可以使用或在C++11中执行此操作,但请记住,列表的O(N)操作都是这样的 #include <iterator> #include <list> .... std::list<Student> l; // look, no pointers!
列表
:
list<Student>* l;
list
中是否有一个函数或方法使其能够执行此操作?std::list
没有随机访问迭代器,因此必须从前面的迭代器开始执行4次。您可以手动执行此操作,也可以使用或在C++11中执行此操作,但请记住,列表的O(N)操作都是这样的
#include <iterator>
#include <list>
....
std::list<Student> l; // look, no pointers!
auto l_front = l.begin();
std::advance(l_front, 4);
std::cout << *l_front << '\n';
对于
std::vector
,您可以使用
myVector.at(i)
//检索第i个元素如果要随机访问元素,应使用向量
,然后可以使用[]
运算符获取第4个元素
vector<Student> myvector (5); // initializes the vector with 5 elements`
myvector[3]; // gets the 4th element in the vector
向量myvector(5);//用5个元素初始化向量`
myvector[3];//获取向量中的第四个元素
这里有一个get()
函数,它返回\u列表中的\i
th学生
Student get(list<Student> _list, int _i){
list<Student>::iterator it = _list.begin();
for(int i=0; i<_i; i++){
++it;
}
return *it;
}
Student get(list _list,int _i){
列表::迭代器it=_list.begin();
对于(int i=0;我希望这与您将帖子从list或vector更改为just list无关注意,此解决方案涉及运行时数组边界检查,因此可能比使用运算符[]慢
@Andrei它可能需要更多的时间,但是它的处理很好。如果容器大小大于n,函数将不会抛出异常(无抛出保证)。否则,行为是未定义的。这就引出了一个问题:为什么?你确定你想要一个列表吗?除了@LightnessRacesinOrbit所说的,如果你确定你需要一个列表
,你确定你想要一个指向列表
?对任何想使用向量的人发出警告,调整它们的大小需要复制
或否除了move
构造函数。如果它不是超时间敏感的,列表可以为您节省很多数据管理方面的麻烦。
vector<Student> myvector (5); // initializes the vector with 5 elements`
myvector[3]; // gets the 4th element in the vector
Student get(list<Student> _list, int _i){
list<Student>::iterator it = _list.begin();
for(int i=0; i<_i; i++){
++it;
}
return *it;
}