简体   繁体   English

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

[英]C++: Access certain element in list of vectors

I have list of vectors: 我有矢量列表:

list< vector<int> > myList;

The structure of this list: 该列表的结构:

({1,2,3}, {4,5,6}, ...)

I want to get a certain element by his positions. 我想从他的职位上获得一定的帮助。 For example, getFromList(myList, 0, 2) will return 3 . 例如, getFromList(myList, 0, 2)将返回3 I tried this, but it does not work: 我试过了,但是不起作用:

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;
}

The solution that Cássio provided in the comments won't work as you cannot randomly access elements of a list Cássio在注释中提供的解决方案将无法使用,因为您无法随机访问list元素

Instead you can use std::next defined in the header <iterator> to do this like so: 相反,您可以使用标题<iterator>定义的std::next来做到这一点,如下所示:

return std::next(myList.begin(), i)->at(j);

Note that this method doesn't do any bounds checking on the size of the list that you pass in. Before returning this you should check that i is a valid index. 请注意,此方法不对传入的列表的大小进行任何边界检查。在返回此列表之前,应检查i是否为有效索引。

Here is a demonstrative program 这是一个示范节目

#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;
}

Its output is 它的输出是

myList[2][3] = 11

Pay attention that the first parameter of the function is const reference. 请注意,该函数的第一个参数是const reference。

As for your function then it has undefined behaviour when one of the indices is out of the valid range because the function returns uninitialized value of variable num . 对于您的函数,当索引之一超出有效范围时,它具有未定义的行为,因为该函数返回变量num未初始化值。

I found some decision on my own: 我自己找到了一些决定:

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