I can’t figure out how to get the link std::stringin std::unordered_mapusing std::reference_wrapper. By the following link, I understand that I need to reload operator==.
Why can't template instances be displayed in `std :: reference_wrapper`?
However, I cannot figure out how to write operator==it to accept const std::reference_wrapper . If the shell was not const , this was not a problem.
Using char instead std::stringworks fine (no overload required operator==).
code:
#include <iostream>
#include <unordered_map>
#include <functional>
bool operator==(const std::reference_wrapper<std::string> lhs,
const std::reference_wrapper<std::string> rhs)
{
return std::equal_to<std::string>()(lhs.get(), rhs.get());
}
int main(){
char chr('a');
std::string str("b");
int num(1);
std::unordered_map<std::reference_wrapper<char>, int, std::hash<char>> charMap;
std::pair<std::reference_wrapper<char>, int> charPair(chr , num);
charMap.insert(charPair);
std::cout << "charMap works. Output: " << charMap[chr] << std::endl;
std::unordered_map<std::reference_wrapper<std::string>, int, std::hash<std::string>> stringMap;
std::pair<std::reference_wrapper<std::string>, int> stringPair(str , num);
stringMap.insert(stringPair);
}
Compilation Error:
error: no match for ‘operator==’ (operand types are ‘const std::reference_wrapper<std::__cxx11::basic_string<char> >’ and ‘const std::reference_wrapper<std::__cxx11::basic_string<char> >’)
{ return __x == __y; }
source
share