The following program iterates over an unordered_map trying to find the best element but doesn't quite return the expected result:
#include <iostream>
#include <unordered_map>
using namespace std;
struct Item
{
int val;
};
int main() {
unordered_map<int, Item> itemMap;
itemMap[0] = {0};
itemMap[1] = {1};
itemMap[2] = {2};
itemMap[3] = {3};
const Item* bestItem = nullptr;
int bestVal = -1;
for (const pair<int, Item>& item : itemMap)
{
if (item.second.val > bestVal)
{
bestVal = item.second.val;
bestItem = &item.second;
}
}
cout << "best val: " << bestVal << " best item: " << bestItem->val;
return 0;
}
Running this program prints out:
best val: 3 best item: 0
This seems to occur because the value_type of a unordered_map is std::pair<const Key, T> but we are iterating over const pair<int, Item>. Sure enough changing this to const pair<const int, Item> results in:
best val: 3 best item: 3
However if we change the type of itemMap to std::map:
map<int, Item> itemMap
Then it doesn't matter if we iterate over const pair<int, Item> or const pair<const int, Item> we get the same result:
best val: 3 best item: 3
Even though the value_type of std::map is still std::pair<const Key, T> . But why?
Aucun commentaire:
Enregistrer un commentaire