Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Providing an iterator for the first element of a container of pairs

I have a container filled with pairs. I want to iterate in it using the STL generic algorithms (in my case it would be inner_product, but consider it as a generic problem). The algorithm I am using expects iterators first and last. Can I provide special iterators first and last that will iterate not on the pairs but on the first element of each pair?

I know i can do it manually, providing a hand-made function object that will be a wrapper around the standard container iterator, deferencing it to the first member of the pair intend of the pair itself,but I think there is also a clever one-liner to do it for me. What would it be?

like image 712
David Reis Avatar asked Nov 23 '08 17:11

David Reis


People also ask

Which function is used to get an iterator to the first element?

begin() function is used to return an iterator pointing to the first element of the map container.

What is a container What is an iterator?

An iterator is an object (like a pointer) that points to an element inside the container. We can use iterators to move through the contents of the container. They can be visualized as something similar to a pointer pointing to some location and we can access the content at that particular location using them.

Which function is used to get a move iterator from a container?

Generally, like this: struct vec{ iterator begin() ; const_iterator begin() const; };

How do you find the iterator element?

Obtain an iterator to the start of the collection by calling the collection's iterator( ) method. Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as hasNext( ) returns true. Within the loop, obtain each element by calling next( ).


1 Answers

I've looked around and found boost::transform_iterator. I've come up with this code. Surprising how well it works:

#include <map>
#include <algorithm>
#include <iostream>
#include <string>
#include <iterator>
#include <boost/iterator/transform_iterator.hpp>
#include <boost/bind.hpp>
#include <boost/function.hpp>

int main() {
    typedef std::map<std::string, int>::value_type value_type;
    std::map<std::string, int> a;
    a["one"] = 1;
    a["two"] = 2;

    // returns the second element 
    boost::function<int(value_type&)> f = boost::bind(&value_type::second, _1);
    std::copy(boost::make_transform_iterator(a.begin(), f), 
              boost::make_transform_iterator(a.end(), f),
              std::ostream_iterator<int>(std::cout, " "));

}

It's printing "1 2 " to the standard output.

like image 149
Johannes Schaub - litb Avatar answered Sep 23 '22 23:09

Johannes Schaub - litb