繁体   English   中英

C ++:访问向量列表中的某些元素

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM