how to insert into an unordered_map for a given struct
Hi,
I have this code which gives me an illegal indirection:
1 2
|
unordered_map<Record, Record, RHash> rmap;
rmap.insert(Record{ "juan"s, 55 }, Record{ "leslie"s, 40 });
|
where Record is defined like this:
1 2 3 4 5 6 7 8 9 10 11
|
struct Record
{
string name;
int product_code;
friend bool operator==(const Record& lhs, const Record& rhs)
{
return lhs.name == rhs.name
&& lhs.product_code == rhs.product_code;
}
}
|
and RHash like this:
1 2 3 4 5 6 7
|
struct RHash
{
size_t operator()(const Record& r) const
{
return hash<string>()(r.name) ^ hash<int>()(r.product_code);
}
};
|
What am I doing wrong??
Thank you in advance... first time dealing with an unordered_map!!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
#include <iostream>
#include <string>
#include <unordered_map>
struct Record
{
std::string name;
int product_code;
friend auto operator<=> ( const Record&, const Record& ) noexcept = default ;
struct hash
{
size_t operator()(const Record& r) const noexcept
{ return std::hash<std::string>()(r.name) ^ std::hash<int>()(r.product_code) ; }
};
};
int main()
{
std::unordered_map< Record, Record, Record::hash > rmap ;
// note: the value_type is std::pair
const bool ok = rmap.insert( /* std::pair */{ Record{ "abc", 1 }, Record{ "def", 2 } } ).second ;
if(ok) std::cout << "ok\n" ;
}
|
http://coliru.stacked-crooked.com/a/936a87cb2e5f3719
You can also use .emplace()
1 2 3 4 5 6 7 8
|
int main()
{
std::unordered_map< Record, Record, Record::hash > rmap ;
const bool ok = rmap.emplace( Record{ "abc", 1 }, Record{ "def", 2 } ).second ;
if(ok) std::cout << "ok\n" ;
}
|
http://coliru.stacked-crooked.com/a/a24f0c3961a9b60d
You can also use c++20 std::piecewise_construct:
1 2 3 4 5 6 7 8 9 10 11
|
int main()
{
std::unordered_map< Record, Record, Record::hash > rmap ;
const bool ok = rmap.emplace(
std::piecewise_construct,
std::forward_as_tuple("abc", 1),
std::forward_as_tuple("def", 2)).second;
if(ok) std::cout << "ok\n" ;
}
|
http://coliru.stacked-crooked.com/a/91d4c412df0b8be4
Last edited on
Thanks!!
Topic archived. No new replies allowed.