我有以下代码:
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();
它的工作没有任何错误,似乎工作正确。但是,我想知道它是否“安全”,因为我将一对long long
传递给find
函数。
谢谢!
2条答案
按热度按时间pcww981p1#
这是不安全的,因为实际比较的值可能不是您所期望的。
两个
long long
值将被转换为int
,然后find
将查找包含这两个转换后的int
值的pair
。由于C++20,因此可以保证此转换产生由int
表示的唯一值,该值等于原始值模2的int
宽度的幂。如果
x
和y
的值落在int
的范围之外,这意味着z
可能会变成false
,即使在集合中可能没有一对x
和y
的值(数学上)等于集合中的对的值。但是,除此之外,没有什么错。从
long long
转换为int
后的搜索将完全按预期工作。edqdpe6u2#
您没有向函数传递一对
long long
。由于没有指定传递给std::set::find
的键的类型,编译器使用构造函数,该构造函数接受对const Key对象的左值引用,即在这种情况下为std::pair<int, int>
。这伴随着您从可能超过
int
范围的值创建std::pair<int, int>
的所有缺点。