Reputation: 3163
I have the following code that looks if a key exists and if so, returns the key and the value:
std::unordered_map<std::string, int64_t> id_to_last_observation({
{"apple", 10},
{"lily", 12},
{"avocado", 2},
{"derry", 5},
{"elephant", 13},
{"monkey", 33},
{"pineapple", 555},
{"car", 1},
{"ireland", 67},
{"family", 48},
{"laptop", 4},
{"ladder", 90}, // element that begins with l that has the highest value
{"computer", 98},
{"travel", 99},
{"orchestra", 65},
{"party", 16},
{"cube", 5},
{"roller-coaster", 8},
{"snake", 0},
{"map", 11},
{"umbrella", 51},
{"lock", 47},
{"person", 92},
{"phone", 89},
{"pen", 81},
});
std::unordered_map<std::string, int64_t>::iterator it;
it = id_to_last_observation.find("ladder");
if (it != id_to_last_observation.end()){
std::cout << "Element Found - ";
std::cout << it ->first<< "::" << it->second<< std::endl;
}else{
std::cout << "Element Not Found" << std::endl;
}return 0;
However, I'm doing it manually here. What I want to do is to get the element that begins with whatever letter I want and that has whatever value (highest, lowest, etc) I want. So If I want the element that begins with l
and that also has the highest value among all elements that begin with l
, I want to return ladder
.
Is there a way to do this efficiently without bruteforcing?
Upvotes: 2
Views: 1381
Reputation: 118340
No, there is no built-in method that does this. That's what "unordered" means. By definition: the values in an unordered map are not stored in any specific order.
Even for a regular, ordered std::map
: the only thing that its available methods will give you, if used wisely, is the range of the keys, but you will still need to search through them all.
Note that either in an unordered_map
or a map
, the values are modifiable, and you can modify the value stored under any key at any time you wish, and the map will not care at all. So, given that, how do you expect your map to even have any way of doing that?
Upvotes: 2