mardi 24 octobre 2017

Sorting a unordered_map with a std::string as a key in lexicographical order

last Week i attended the Catalysts Coding Contest and now i am trying to recreate the Task with more High-Level C++. So I decided to use a std::unordered_map consisting of a std::string as the key value and a double as the mapped type.

The Data looks like this:

N0 1.23
N1 2.45

and so on.

Now the Problem is that i want to sort this by the string. But it always messes up when trying to sort bigger numbers like

N3 1.23
N10 4.56

because 1 < 3 and it is comparing it character for character. Now i already tried the std::sort function, but i don't really understand how the 3rd Parameter works.

I hope somebody can explain it to me or has a clue how to solve this.

Here is the relevant source code:

std::unordered_map <std::string, unsigned int> network;
unsigned int network_power = 1234;
std::unordered_map <std::string, double> network_percent;

for (std::pair<std::string, unsigned int> element : network) {
    double x = ((double)element.second / (double)network_power) * 100;
    x = (int)(x * 100 + 0.5) / 100.0;

    network_percent.insert({element.first, x});
}

In the end it should Output each element of network_percent in ascending order.

Thanks in advance Philipp

PS: I already found the other articles on StackOverflow, but don't understand them.

Aucun commentaire:

Enregistrer un commentaire