jeudi 22 novembre 2018

Unordered map iterating by values

I have a weird issue that I don't know if I am miss reading the documentation or my computer is doing something strange.

I have an unordered_map. I want to iterate over the buckets of the unordered_map in bucket order. This part is important as I need the access to be relatively random. I searched over cppreference.com and I found this. The code is as follows:

// unordered_map::bucket
#include <iostream>
#include <string>
#include <unordered_map>
int main ()
{
  std::unordered_map<std::string,std::string> mymap = {
    {"us","United States"},
    {"uk","United Kingdom"},
    {"fr","France"},
    {"de","Germany"}
  };

  for (auto& x: mymap) {
    std::cout << "Element [" << x.first << ":" << x.second << "]";
    std::cout << " is in bucket #" << mymap.bucket (x.first) << std::endl;
  }

  return 0;
}

The output I was expecting and wanted on my computer was

Element [us:United States] is in bucket #1
Element [de:Germany] is in bucket #2
Element [fr:France] is in bucket #2
Element [uk:United Kingdom] is in bucket #4

However the output I am getting is instead sorted by value type which is strange

Element [de:Germany] is in bucket #2
Element [fr:France] is in bucket #3
Element [uk:United Kingdom] is in bucket #1
Element [us:United States] is in bucket #1

I even tried replacing the value with a class that had no comparison operators and it still was able to sort them. Is this something with the way my computer is storing the map or is cpprefernce outdated? I was able to iterate over the buckets through a loop like this:

for ( unsigned int i = 0; i < b.bucket_count(); ++i) {

    for ( hash_table::const_local_iterator image_iterator = 
    b.begin(i);image_iterator!= b.end(i); ++image_iterator ){

The only issue is that I need to be able to skip a certain number of values i.e. I only want 1 item for every 100 which requires complicated loops and is slow.

Any help would be appreciated. I can't seem to figure this out!

Aucun commentaire:

Enregistrer un commentaire