I am trying to use boost :: make_transform_iterator to create an iterator for a custom class whose data is stored on a map and where the iterator uses a key vector to access the values.
In my problem, map values โโare containers containing big data. Since I cannot afford to copy the data, I would like to access the data by reference via an iterator. However, the data is corrupted, as can be seen from the output of a simple example that I attached.
As far as I can tell, the problem is using the from_key functor, which is initialized using the map link and boost :: make_transform_iterator semantics.
Any ideas how I could do this correctly using boost?
Thank,
Patrick
#include <iostream>
#include <string>
#include <vector>
#include <boost/unordered_map.hpp>
#include <boost/iterator/transform_iterator.hpp>
#include <boost/assign.hpp>
#include <boost/assign/std/vector.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>
#include <boost/ref.hpp>
using namespace boost::assign;
namespace bl = boost::lambda;
class holder
{
public:
holder() : v() {};
holder( const std::vector<double>& in ) : v(in) {};
std::vector<double>& vector() { return v; };
const std::vector<double>& vector() const { return v; };
private:
std::vector<double> v;
};
class from_key
{
public:
typedef holder result_type;
from_key( const boost::unordered_map<std::string, holder >& m ) : map_(m) {};
const holder& operator() ( const std::string& in ) const { return map_.at(in); };
private:
const boost::unordered_map<std::string, holder >& map_;
};
typedef boost::transform_iterator<from_key, std::vector<std::string>::iterator > iterator;
int main()
{
std::vector<std::string> keys;
keys += "1","2","3";
std::vector<double> vals;
vals += 1.0, 2.0, 3.0;
holder h(vals);
boost::unordered_map<std::string, holder > m;
insert( m ) ( "1", h )
( "2", h )
( "3", h );
iterator it = boost::make_transform_iterator( keys.begin(), from_key( m ) );
iterator end = boost::make_transform_iterator( keys.begin(), from_key( m ) );
const std::vector<double>& v = it->vector();
std::for_each( vals.begin(), vals.end(), std::cout << bl::_1 << " " );
std::cout << std::endl;
std::for_each( v.begin(), v.end(), std::cout << bl::_1 << " " );
std::cout << std::endl;
}