[英]C++: Access certain element in list of vectors
我有矢量列表:
list< vector<int> > myList;
該列表的結構:
({1,2,3}, {4,5,6}, ...)
我想從他的職位上獲得一定的幫助。 例如, getFromList(myList, 0, 2)
將返回3
。 我試過了,但是不起作用:
int getFromList(list< vector<int> > myList, int i, int j)
{
int ki = 0, kj = 0, num;
for (list<vector<int>>::iterator it1 = myList.begin(); it1 != myList.end(); ++it1) {
vector<int>::iterator it2;
ki++;
for (it2 = (*it1).begin(); it2 != (*it1).end(); ++it2) {
kj++;
if (ki == i && kj == j) {
num = (*it2);
}
}
}
return num;
}
Cássio在注釋中提供的解決方案將無法使用,因為您無法隨機訪問list
元素
相反,您可以使用標題<iterator>
定義的std::next
來做到這一點,如下所示:
return std::next(myList.begin(), i)->at(j);
請注意,此方法不對傳入的列表的大小進行任何邊界檢查。在返回此列表之前,應檢查i
是否為有效索引。
這是一個示范節目
#include <iostream>
#include <list>
#include <vector>
#include <iterator>
#include <stdexcept>
int getFromList( const std::list<std::vector<int>> &myList, size_t i, size_t j )
{
if ( !( i < myList.size() ) ) throw std::out_of_range( "The frst index is out of the range" );
auto it = std::next( myList.begin(), i );
if ( !( j < it->size() ) ) throw std::out_of_range( "The second index is out of the range" );
return it->operator []( j );
}
int main()
{
std::list<std::vector<int>> myList = { { 1, 2, 3 }, { 4, 5, 6, 7 }, { 8, 9, 10, 11, 12 } };
std::cout << "myList[" << 2 << "][" << 3 << "] = " << getFromList( myList, 2, 3 ) << std::endl;
return 0;
}
它的輸出是
myList[2][3] = 11
請注意,該函數的第一個參數是const reference。
對於您的函數,當索引之一超出有效范圍時,它具有未定義的行為,因為該函數返回變量num
未初始化值。
我自己找到了一些決定:
int getFromList(list< vector<int> > myList, int i, int j)
{
list<vector<int>>::iterator iter = myList.begin();
advance(iter, i);
vector<int> x = (*iter);
return x[j];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.