列表中的C ++迭代器

时间:2016-11-07 13:33:34

标签: c++ list iterator

我对list上的迭代器有疑问。在function我必须比较double s,但我不知道如何从第二级获取元素,只有迭代器到第一级。

void function (std::list<std::list <double>>::iterator *begin, std::list<std::list <double>>::iterator *end)
{
    //do something
}

int main()
{
    std::list <std::list <double>> a_list;
    function (a_list.begin(), a_list.end());
}

2 个答案:

答案 0 :(得分:1)

void function (list<list <double> >::iterator begin, list<list <double> >::iterator end)
{
    for(std::list<std::list <double> >::iterator it =begin;it!= end;it++)
    {
        for(std::list <double>:: iterator it_inner = (*it).begin(); it_inner != (*it).end();it_inner++)
        {
            printf("%f ",*it_inner );
        }
        printf("\n");
    }

}



int main()
{
    std::list <std::list <double> > a_list;
    for(int i=0;i<=3;i++)
    {
        std::list <double> inner_list;
        for(double j=0;j<=8;j+=2.2)
        {
            inner_list.push_back(j);
        }
        a_list.push_back(inner_list);
    }    
    function (a_list.begin(), a_list.end());
}

答案 1 :(得分:0)

您可以将迭代器作为参数传递,也可以只传递整个列表,如下所示:

#include <iostream>
#include <list>

using namespace std;

void funcA (list<list<double>>::iterator begin, list<list<double>>::iterator end) {
    //do something

    list<double>::iterator sublist1 = begin->begin();
    cout << *sublist1 + 1 << endl;
}

void funcB (list<list<double>> list) {

    for (auto&& sublist: list) {
        for (auto&& value: sublist) {
            cout << value << ' ';
        }
    }
    cout << endl;
}


int main() {
    list <list<double>> a_list = {{1,2,3},{4,5,6}};

//  list<list<double>>::iterator a = a_list.begin();
//  list<double>::iterator b = a->begin();
//  
//  cout << *b + 2 << endl;

    funcA(a_list.begin() , a_list.end());
    funcB(a_list);
}