如何从 C++ List 中获取指定索引处的元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16747591/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 20:36:44  来源:igfitidea点击:

How to get an element at specified index from c++ List

c++listget

提问by user2398815

I have a list:

我有一个list

list<Student>* l;

and I would like to get an element at a specified index. Example:

我想在指定的索引处获取一个元素。例子:

l->get(4)//getting 4th element

Is there a function or method in listwhich enables it to do so?

是否有一个函数或方法list可以让它这样做?

回答by juanchopanza

std::listdoes not have a random access iterator, so you have to step 4 times from the front iterator. You can do this manually or with std::advance, or std::nextin C++11, but bear in mind that both O(N) operations for a list.

std::list没有随机访问迭代器,所以你必须从前面的迭代器开始 4 次。您可以手动或使用std::advance或C++11 中的std::next执行此操作,但请记住,列表的两个 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';

Edit: The original question asked about vector too. This is now irrelevant, but may be informative nonetheless:

编辑:原始问题也询问了向量。这现在无关紧要,但仍然可以提供信息:

std::vectordoes have random access iterators, so you can perform the equivalent operation in O(1) via the std::advance, std::nextif you have C++11 support, the []operator, or the at()member function:

std::vector确实具有随机访问迭代器,因此如果您有 C++11 支持、运算符或成员函数,则可以通过std::advance, std::next在 O(1) 中执行等效操作:[]at()

std::vector<Student> v = ...; 
std::cout << v[4] << '\n';    // UB if v has less than 4 elements
std::cout << v.at(4) << '\n'; // throws if v has less than 4 elements

回答by Patch92

Here's a get()function that returns the _ith Studentin _list.

这里有一个get()返回函数_iStudent_list

Student get(list<Student> _list, int _i){
    list<Student>::iterator it = _list.begin();
    for(int i=0; i<_i; i++){
        ++it;
    }
    return *it;
}

回答by srikanta

If you want random access to elements, you should use a vectorand then you can use []operator to get the 4th element.

如果你想随机访问元素,你应该使用 avector然后你可以使用[]运算符来获取第 4 个元素。

vector<Student> myvector (5); // initializes the vector with 5 elements`
myvector[3]; // gets the 4th element in the vector

回答by simpleuser

For std::vectoryou can use

因为std::vector你可以使用

myVector.at(i)//retrieve ith element

myVector.at(i)//检索第i个元素