Reputation: 33
I am beginning with vector and unordered_map in C++. But I don't understand the reason of the error when accessing a value of the map by its key.
First I define a vector of integers as follows :
std::vector <int> vec;
vec.push_back(1);
vec.push_back(5);
vec.push_back(1);
then I convert the vector to a string:
std::ostringstream oss;
if (!vec.empty())
std::copy(vec.begin(), vec.end(),std::ostream_iterator<int>(oss));
std::string s = oss.str();
const void * s1=s.c_str();
and I create my map :
std::unordered_map<const void *, const void *> map1;
map1[s1]="Hello";
Here, if s1 is equal to "151", why can't I obtain the value "Hello" of the key "151" like this :
std::cout << (char *) map1["151"] << std::endl;
unlike this :
const char* s2 = "180"
map1[s2]="World"
std::cout <<"The value of the key '180' :" << (char *) map1["180"] << std::endl;
Here, I can have "The value of the key '180' : World" displayed.
So what is really s1 ? Isn't it the string "151" ?
Upvotes: 2
Views: 1113
Reputation: 172894
From the view of a std::unordered_map<const void *, const void *>
, map1[s1]
is different from map1["151"]
, because the unordered_map
just compare the key by the value of the pointer, not the value the pointer points to.
And in the 2nd code, s2
points to the literal c-style string "180"
, so map1[s2]
and map1["180"]
could get the same value, because they're pointing to the same thing.
According to the declaration of std::unordered_map,
template<
class Key,
class T,
class Hash = std::hash<Key>,
class KeyEqual = std::equal_to<Key>,
class Allocator = std::allocator< std::pair<const Key, T> >
> class unordered_map;
std::unordered_map
use std::equal_to as its default key comparer, which just use operator==
for comparing.
You can provide your own comparer for std::unordered_map
to change the behaviour, like
std::unordered_map<const void*, const void*, std::hash<const void*>, my_comparer> map1;
Upvotes: 4