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?
begin() function is used to return an iterator pointing to the first element of the map container.
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.
Generally, like this: struct vec{ iterator begin() ; const_iterator begin() const; };
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( ).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With