簡體   English   中英

如何從c ++ List獲取指定索引處的元素

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

我有一個list

list<Student>* l;

我想在指定的索引處獲取一個元素。 例:

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

是否有一個函數或方法list ,使它能夠這樣做呢?

std::list沒有隨機訪問迭代器,所以你必須從前迭代器步驟4次。 您可以手動或使用std :: advancestd :: next在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確實有隨機訪問迭代器,因此你可以通過std::advancestd :: next在O(1)中執行等效操作,如果你有C ++ 11支持, []運算符或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

這是一個get()函數,它返回_list_i Student

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

如果要隨機訪問元素,則應使用vector ,然后可以使用[]運算符獲取第4個元素。

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

對於std::vector您可以使用

myVector.at(i) //檢索第i個元素

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM