tags:

views:

132

answers:

2

I have an std::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?

+7  A: 

You probably want to use a Boost::bimap instead of a normal map -- it provides this capability quite directly.

Jerry Coffin
I would, but I can't. I cannot take that code into my code base due to license restrictions.
Steven Behnke
Which restrictions ? Boost License has been designed so that it could in fact get included in any project, commercial or not and is probably the most permissive I know of (right along the BeerWare).
Matthieu M.
The Boost license is one of the most permissive ones, what problem do you have with it?
Matteo Italia
I work for a gaming company that has to submit code for legal compliance reasons. It is more of a fight than I'm willing to take up for boost.
Steven Behnke
@Stephen: I take it that by "gaming" you mean gambling, since I can't imagine a first-person shooter with legal compliance constraints. Are you sure it wouldn't be worth it to argue for the use of Boost? It's very useful, and if it's only one fight for indefinite use of Boost it might be a good idea. Then again, you know your constraints lots better than I do, and if you really can't feasibly use Boost you have my sympathy.
David Thornley
+1  A: 

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);
Mike Seymour