Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does std:set check if there is an equivalent element in set during the insertion?

Let's use the following code as an example.

auto cmp = [](ll a, ll b) {
    return gcd(12, a) < gcd(12, b);
};
set<ll, decltype(cmp)> s(cmp);
for(ll i = 0; i < 2; i++){
    ll x;
    cin >> x;
    s.insert(x);
    cout << "Success! \n";
}

I defined new comparator that compares numbers by their greatest common divisor with 12.

First I successfully inserted 5. And then I tried to insert 7, but it was not successful.

I know that gcd(12, 5) = gcd(12, 7) = 1.

But I am failing to understand how does std::set check if 5 is equivalent to 7.

It can find out that gcd(12, 7) is not less than gcd(12, 5) using comparator comp I gave it, but how does it figure out that gcd(12, 7) is equal to gcd(12, 5)?

like image 516
Shynggys Saparbek Avatar asked Jan 01 '21 22:01

Shynggys Saparbek


People also ask

How do you check if an element exists in a set?

Using find() function The standard solution to check for existence of an element in the set container ( std::set or std::unordered_set ) is to use its member function find() . If the specified element is found, an iterator to the element is returned; otherwise, an iterator to the end of the container is returned.

How does std::set work?

std::set is an associative container that contains a sorted set of unique objects of type Key . Sorting is done using the key comparison function Compare. Search, removal, and insertion operations have logarithmic complexity. Sets are usually implemented as red-black trees.

How do you check if an element is in a set in CPP?

set find() function in C++ STL The set::find is a built-in function in C++ STL which returns an iterator to the element which is searched in the set container. If the element is not found, then the iterator points to the position just after the last element in the set.

What happens when we insert duplicate values in set C++?

In Set duplicate values are not allowed to get stored. On other hand in case of MultiSet we can store duplicate values. In case of Set, one cannot change the value once it gets inserted however we can delete or insert it again. However in case of MultiSet also we cannot change the value once get inserted.


1 Answers

It calls the comparator twice, with different order of arguments.

If cmp(x, y) and cmp(y, x) are both false, then x and y are considered to be equivalent.

like image 129
HolyBlackCat Avatar answered Sep 22 '22 04:09

HolyBlackCat