custom structure <set> contains duplicates

I am learning C ++. I am stuck in this problem.

I found that it contains a custom structure containing two long ints a and b. I have a custom comparison structure that compares numbers and returns true if either a or b are different.

typedef long int li; struct number { number(li a1,li b1): a(a1), b(b1) {} li a, b; }; struct compare { bool operator() (const number &lhs, const number& rhs) const{ return lhs.a != rhs.a || lhs.b != rhs.b; } }; int main() { set<number, compare> nums; nums.insert(number(1, 2)); nums.insert(number(1, 1)); nums.insert(number(2, 1)); nums.insert(number(1, 2)); for (auto &i : nums) { cout << ia << " " << ib << endl; } return 0; } 

Result here

12

2 1

eleven

12

It has two entries 1 2 . Any clarification would be appreciated.

+6
source share
2 answers

Your comparison function should return whether some element is less than another, and not whether they are equal. (More formally, he should define "Strict Weak Order" on the elements of your set.)

Use something like

 struct compare { bool operator() (const number &lhs, const number& rhs) const{ return std::tie(lhs.a, lhs.b) < std::tie(rhs.a, rhs.b); } }; 

If you don't need to order, you can define a suitable hash function for your type and use std::unordered_set .

To avoid such future problems, be sure to read the documents . They clearly explain what your comparison function should do.

For reference: std::tie , as used above, builds tuples of links to its arguments, which can then be compared lexicographically with < . This is a simple, general, and quick way to create some sort of ordering for collections of less than comparable materials.

+6
source

Your comparison function must meet strict / weak order requirements.

(I really prefer the answer using std::tie , but this may be more indicative for beginners)

 bool compare(const number& lhs, const number& rhs) { if(lhs.a < rhs.a) return true; else if(lhs.a > rhs.a) return false; else return lhs.b < rhs.b; } 
+5
source

Source: https://habr.com/ru/post/1012838/


All Articles