c++11 - How to insert a reference to a multimap? -
i have class foo
contains multimap unsigned long
, reference
bar class
.
i'm getting error "no matching function call multimap, etc".
what wrong on insert multimap?
[header file]
class foo { public: foo(); ~foo(); void set(const unsigned long var1, const bar& var2); private: struct map_sort { bool operator()(const unsigned long& e1, const unsigned long& e2) const { return (e2 < e1); } }; std::multimap<unsigned long,bar&, map_sort> m_map; };
[source file]
void foo::set(const unsigned long var1, const bar& var2) { m_map.insert(var1,rtime); //<-- error!!!!!!!! }
you multimap member declared take unsigned long
, bar&
std::multimap<unsigned long,bar&, map_sort> m_map;
while, in source file
void foo::set(const unsigned long var1, const bar& var2) { m_map.insert(var1,rtime); //var1 const here! (rtime not declared assume meant var2 - const, too) }
you trying insert const unsigned long
, const bar&
differ ones declared above (they constant). note const unsigned long
isn't issue because copied value so, in fact, multimap keeps own version of variable , "main" 1 can't modified whatsoever.
additionally, check out documentation of multimap's insert
method http://www.cplusplus.com/reference/map/multimap/insert/. should use std::pair
insert key-value pair:)
solution 1: change method take non-const arguments:
void set(unsigned long var1, bar& var2);
solution 2: change map contain const values:
std::multimap<const unsigned long, const bar&, map_sort> m_map
working example:
class foo { public: foo(); ~foo(); void set(const unsigned long var1, const bar& var2); private: struct map_sort { bool operator()(const unsigned long& e1, const unsigned long& e2) const { return (e2 < e1); } }; std::multimap<const unsigned long, const bar&, map_sort> m_map; }; void foo::set(const unsigned long var1, const bar& var2) { m_map.insert(pair<const unsigned long, const bar&>(var1, var2)); }
Comments
Post a Comment