Search code examples
c++c++14stdlist

Iterating over specific items of a pair (or tuple) in a list in C++


Say I have something like:

using MyList = std::list<std::pair<string,int>>;

How can I get an iterator to just the strings (or ints) of the list? I have a function I'd like to pass something.begin() and something.end() that is just of the ints. Is there an easy/clever/slick way to do this? Can it be done with a tuple as well?


Solution

  • There is Boost's transform_iterator.

    using MyList = std::list<std::pair<string,int>>;
    
    MyList l{ {"Hello", 42}, {"World", 0} };
    
    auto tr = [](auto const& p){
        return p.first;
    };
    
    copy(boost::make_transform_iterator(l.begin(), tr),
         boost::make_transform_iterator(l.end(), tr),
         ostream_iterator<string>(cout, ", "));
    

    live example