Next value in std::map
I have an 开发者_如何学Gostd::map<std::string, float>
so I can do quick lookups for float values based on names, but I have a situation now where I need to find the next float value in the list as if it were sorted numerically. I cannot just use an iterator, as far as I know, since the map is key sorted. So if my set contains:
std::pair<"One", 1.0>
std::pair<"Two", 2.0>
std::pair<"Three", 3.0>
std::pair<"Four", 4.0>
std::pair<"Five", 5.0>
If I want to find the next value after "Three", what would be the most efficient way to do this? The expected output in this case would be 4.0. I can iterate over the whole list and store the max value along with the current next value. Is this the best way?
You probably want to use a Boost::bimap instead of a normal map -- it provides this capability quite directly.
If you really can't use Boost, then you could keep a separate set of floats alongside the map (being very careful to keep them synchronised). Then you can find what you want with two lookups:
set<float>::const_iterator found = set.find(map["Three"]);
++found;
assert(*found == 4.0);
精彩评论