我有一个 std::set
包含 std::pair<T1, T2>
类型的值按对的第一个值排序:
struct Comparator
{
bool operator() (const std::pair<T1, T2>& lhs, const std::pair<T1, T2>& rhs) const
{
return lhs.first < rhs.first;
}
}
我的定义是std::set<std::pair<T1, T2>, Comparator> s
.
但是当我尝试插入具有相同第一个值的对时,元素插入到之前的集合中(第二个值不同)。该集不插入它。
我想要 std::set
只有当对的第二个值相等(或第一个和第二个相等)时,才将元素视为相等。怎么做??
附言我不想使用 boost 库。
最佳答案
But when I try to insert pair with the same first value with element inserted to the set before (second value is different). The set does not insert it.
好吧,这就是您所要求的。你的比较器只看 first
成员(member)和一个std::set
不允许重复条目。我猜你可能想按 first
排序成员优先,如果相等,则由 second
.因此,将您的比较器更改为如下所示:
struct Comparator
{
bool operator() (const std::pair<T1, T2>& lhs,
const std::pair<T1, T2>& rhs) const
{
if (lhs.first == rhs.first)
return lhs.second < rhs.second;
else
return lhs.first < rhs.first;
}
}
请注意,这是默认运算符 <
对于 std::pair
would do anyway因此,如果您需要此特定顺序,只需使用默认值即可。
关于c++ - std::set with std::pair - 如何为元素编写比较器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27893968/