Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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 although there is no 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading