jeudi 5 mars 2015

C++: Error outputting a custom hash key value from unordered_map to std::cout


I am trying to build an std::unordered_map with a custom type as a key. The custom type is a simple std::vector<double>. The idea is that it will function as a convenient container for 2D points on a grid. Everything is working correctly except for outputting the hashed key. Here is a sample I put together to illustrate the idea:





#include <iostream>
#include <vector>
#include <unordered_map>
#include <boost/functional/hash.hpp>
#include <chrono>

namespace std{
template<typename Container>
struct hash {
std::size_t operator()(Container const& v) const
{
return boost::hash_range(v.begin(), v.end());
}
};
}

int main()
{

std::unordered_map<std::vector<double>, double> test;

unsigned long t = (unsigned long) std::chrono::system_clock::now().time_since_epoch().count();
std::srand(t);
for (uint i = 0; i < 100 ; ++i)
{
double d1 = i/200.0;
double d2 = i/200.0;
std::vector<double> v({d1, d2});
test[v] = d1;
}

std::cout << "Size:" << test.size() << std::endl;
for (const auto& it : test )
{
std::cout << it.first << ":" << it.second << std::endl;
}

return 0;
}



The hash specialisation template is courtesy of another SE thread. The trouble is that g++ spits out the following error when I try to compile the above:





cannot bind 'std::ostream {aka std::basic_ostream<char>}' lvalue to 'std::basic_ostream<char>&&'
std::cout << it.first << ":" << it.second << std::endl;
^



It is obvious that it stumbles on it.first. The code compiles and runs correctly if I remove it.first. I understand that the output will not be a vector of doubles. I did look around SE for quite a while, but I couldn't find a definitive answer on how to std::cout the hash value from an unordered map with a custom key type. Any feedback will be highly appreciated.


Thank you in advance!




Aucun commentaire:

Enregistrer un commentaire