给定std::set< T, less >
或std::map< T, less >
包含独特元素的容器。less
是异构比较器。即它可以将其他类型U
的值与 type 的值进行比较T
。尽管 type 的所有值T
都是唯一的,但(可能)有很多 type 的值T
,它们比较等于 type 的某个特定值U
。它是未定义的行为吗?
说,我想在容器中找到(一个)元素,它有键,相当于 type 的值U
。任何一个:第一个、最后一个或中间(如果有多个)。我知道,容器中有多个元素,相当于u
type的值U
。我可以使用std::set::find
或std::map::find
发挥作用吗?它是未定义的行为吗?
示例(此处与公差的比较不精确0.2
):
#include <set>
#include <iostream>
double const eps = 0.2;
struct less
{
bool operator () (double l, double r) const { return l < r; }
using is_transparent = void;
bool operator () (int l, double r) const { return l + eps < r; }
bool operator () (double l, int r) const { return l + eps < r; }
};
int main()
{
std::set< double, less > s{0.0, 0.9, 1.0, 1.1, 2.0};
for (auto it = s.find(1); it != std::end(s); it = s.find(1)) {
std::cout << *it << ' ';
s.erase(it);
}
}
输出(通常未指定顺序):
0.9 1 1.1
如上所述使用独特元素的关联有序容器是否是UB?
我应该使用std::multiset
andstd::multimap
代替吗?