Search code examples
c++setstd-pairstdset

Is passing a pair of long long in set find safe?


I have the following code:

std::set<std::pair<int, int>> my_set;

long long x = (some value);
long long y = (some value);

// should be true if x or y exceed the limits of int
bool z = my_set.find({x, y}) == my_set.end();

It works without any errors and seems to work correctly. But, I wonder if it's 'safe' because I am passing a pair of long long to the find function.

Thanks!


Solution

  • It is not safe in as far as the values that will actually be compared may not be what you expect.

    The two long long values will be converted to int and then find will look for a pair containing these two converted int values. Since C++20 it is guaranteed that this conversion produces the unique value represented by int that is equal to the original value modulo 2 to the power of the width of int.

    If the values of x and y will fall outside the range of int, this means that z may become false even though there may not be a pair in the set for which the values of x and y are (mathematically) equal to those of the pair in the set.

    However, aside from that, there is nothing wrong. The search after conversion from long long to int will work exactly as expected.