pawel112
pawel112

Reputation: 111

C++ iterators in lists

I have a question about iterators on lists. In function I have to compare the doubles, but I don't know how to get the elements from the second level, with only iterators to the first level.

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

Upvotes: 0

Views: 100

Answers (2)

chinmay rakshit
chinmay rakshit

Reputation: 322

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

Upvotes: 1

Daniel Illescas
Daniel Illescas

Reputation: 6126

You can pass the iterators as parameters or just the entire list, like this:

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

Upvotes: 0

Related Questions