vertigo wrote:
> Hello
>
> I have std::map object and i want to have randomly sorted objects in it.
> I tried to:
>
> std::map<int,RandomCompare> myobject;
>
> and:
> struct RandomCompare{
> bool operator(int i1, int i2){
> /* what shuold i put here ??? */
> }
> }
>
> I see that i can only return true or false, but shouldn't it return int
> to indicate 3 possibilities: equal, greater, smaller ?
>
> When i put there: return rand()%2; after adding several object's i have
> only some of them (because of true which symbols equality ??).
>
> How can i solve my problem ?
> I want to have all objects but while they are added always in the same
> order i want to read them (using iterator) in randomly order.
>
> Thanx
> Michal
Your approach (a comparator which returns a random result) will not work
because a map cannot contain two objects which compare equal. For a
map, a equals b if neither of the following is true: a < b, b < a.
Since your comparison function is random, there's a good chance that any
two objects will compare equal and the insert will not take place. Even
worse, you'll get unpredictable (probably undefined) behavior since the
comparison value changes arbitrarily and the map internally probably
assumes its elements are in sorted order.
Instead of (ab)using a map like this, why don't you use a vector and
random_shuffle?
Mark
|