Re: using a float as the index in an STL map?
On Apr 21, 12:36 am, zeppethef...@gmail.com wrote:
On 20 Apr, 22:33, "Victor Bazarov" <v.Abaza...@comAcast.net> wrote:
That's fine. Another way is to have a vector<pair<float,int> >, stuff
it with all the pairs you encounter, then sort them based on the pair's
'.first' member. You'd have better space economy that way. Of course,
in that case if you need to extract the correct order at any moment,
you'd have to sort right there (whereas 'std::map' always keeps them
sorted).
Uhm, I don't think it would be the best idea, because every time you
have to add a number you have to perform a search that is linear,
while the access to the map is logarithmic.
Why would the search have to be linear? I've used lower_bounds
to keep a vector sorted on more than a few occasions.
But the real question concerns the actual use. I got the vague
impression that the ordering was only relevant once the
collection had been constructed. If that's the case, the best
solution is probably to just add the values to a vector, and
sort once at the end, when the vector is full. Otherwise, it
depends.
I think a good alternative would be to manually define the comparison
operator "less" considering that the equality
(a == b)
on a map is given by
!less(a,b) && !less(b,a)
it should be sufficient to write less() as something like
less(a, b){
if (a - b > threshold)
return false;
else
return true;
}
with threshold a proper small number.
That's a nice way to get undefined behavior. Since such a
function doesn't define an ordering relationship (which must be
transitive), it doesn't meet the requirements for std::map or
std::set.
--
James Kanze (Gabi Software) email: james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34