1

I'm having a strange problem using an unordered_map with key type uint64_t and value type uint8_t. (I have a few potentially large integers that I want to count with the uint8_t values.) Here's some code:

std::unordered_map<uint64_t,uint8_t> mymap;
mymap.emplace(2,1);
mymap.emplace(20,3);
mymap.emplace(200,34);

for (auto it = mymap.begin(); it != mymap.end(); ++it) {
    std::cout << it->first << ":" << it->second << std::endl;
    printf("%lld : %d\n", it->first, it->second);
}

It appears that the keys and values are saved perfectly fine in the unordered_map. But, the std::cout << it->second << std::endl; code is garbling the output of the uint8_t values. That is, cout (the first line in the for loop) garbles the output, while the old school cstdio printf (the second line in the for loop) prints out the values just fine. Weird. Any idea as to what is happening here?

If I change the unordered_map to <uint64_t,uint16_t> or <uint64_t,int>, it works perfectly fine. I've tried various terminal and pseudo terminal environments plus text files, all with garbled or missing outputs for the uint8_ts. I'm stumped.

Here is the output:

20:
20 : 3
200:"
200 : 34
2:
2 : 1
Mooing Duck
  • 64,318
  • 19
  • 100
  • 158
user134770
  • 19
  • 2

3 Answers3

2

Note: There are no formatted input functions taking a signed or unsigned char in the iostream library. Hence the the uint8_t is converted and interpreted as character.

std::cout << it->first << ":" << ùnsigned(it->second) << std::endl; will fix it.

0

You could do a cast:

std::cout << int(it->second);
Yifu Wang
  • 313
  • 2
  • 9
0

It seems that type uint8_t is an alias for type unsigned char. If you will cast the value to unsigned int you will get the same result as with printf.

for (auto it = mymap.begin(); it != mymap.end(); ++it) {
    std::cout << it->first << ":" << ( unsigned int )it->second << std::endl;
    printf("%lld : %d\n", it->first, it->second);
}

As for your original code there is used the following operator for uint8_t

template<class traits>
basic_ostream<char,traits>& operator<<(basic_ostream<char,traits>&,
unsigned char);
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335