C ++ std :: set compator

This is the code:

struct comp { bool operator()(Reputation *one, Reputation *two) { if (one->Amount < 0 && two->Amount >= 0) return false; if (one->Amount >= 0 && two->Amount < 0) return true; if (one->Amount >= 0) return one->Amount <= two->Amount; else return one->Amount >= two->Amount; } }; 

And this is the problem:

Failed to run debug check!
File: .. \ VC \ include \ xtree
Line: 638

Expression: invalid operator <

After that I can choose "Abort", "Retry" or "Ignore". If I choose to ignore many others (identical), they will appear, but it works fine.

The problem occurs when I insert Reputation with β†’ Amount == in one of the previously added Reputations *, but I'm not sure about the latter.

Any help would be greatly appreciated.

EDIT: the order I want them to be ordered is first positive in ascending order, and then negative in desc order. Example: 1 5 10 11 11 20 50 -1 -5 -50

+2
source share
3 answers

You must define a nonreflective relationship, like < - so change <= to < and '> =' to '>' in the last pair of comparisons in your method. This is what VC ++ diagnoses.

In addition, if a correctly encoded operator <- specified, if two elements a and b are such that a <b and b <a are both false, these elements are considered equivalent, and therefore only one will be inserted into the set (it does not matter if the elements can be distinguished by any other comparison: only the equivalence relation implied by the comparator matters).

+6
source

Elements in std::set must be unique! (and less comparable) If you want to have multiple elements with the same value (for example, the provided sample), use std::multiset .

see http://www.cppreference.com/wiki/stl/set/start and http://www.cppreference.com/wiki/stl/multiset/start

+1
source

You cannot insert the same values ​​into std :: set, this requires unique values. Use std :: multiset.

For your ridiculous order, this seems to work:

 struct comp { bool operator()(const Reputation *a, const Reputation *b) { if (a->Amount < 0 && b->Amount < 0) return a->Amount > b->Amount; else if (a->Amount < 0) return false; else if (b->Amount < 0) return true; else return a->Amount < b->Amount; } }; 
0
source

All Articles