std::set 与 std::pair - 如何为元素编写比较器 [英] std::set with std::pair - how to write comparator for elements
问题描述
我有一个 std::set
包含 std::pair
类型的值,按对的第一个值排序:>
I have a std::set
containing values of the type of std::pair<T1, T2>
with order by first value of the pair:
struct Comparator
{
bool operator() (const std::pair<T1, T2>& lhs, const std::pair<T1, T2>& rhs) const
{
return lhs.first < rhs.first;
}
}
我的定义是std::set
.
但是当我尝试插入具有相同第一个值的对并且元素之前插入到集合中时(第二个值不同).集不插入.
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.
我希望 std::set
仅在对的第二个值相等(或第一个和第二个相等)时才将元素视为相等.怎么做??
I'd like to have std::set
that treats elements as equal only where second value of the pair is equal (or first and second are equal). How to do that??
附言我不想使用 boost 库.
P.S. I don't want to use boost library.
推荐答案
但是当我尝试插入具有相同第一个值的对并且元素之前插入到集合中时(第二个值不同).集不插入.
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
成员,并且 std::set
不允许重复条目.我猜您可能希望首先按 first
成员排序,如果相等,则按 second
排序.因此,将比较器更改为如下所示:
Well, that's what you've asked for. Your comparator only looks at the first
member and a std::set
does not allow for duplicate entries. I guess that you probably want to sort by the first
member first and if that is equal, by the second
. Hence, change your comparator to something like this:
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
的默认运算符 <
无论如何都可以 所以如果你想要这个特定的顺序,只需使用默认值.
Note that this is what the default operator <
for std::pair
would do anyway so if you want this particular ordering, simply use the default.
这篇关于std::set 与 std::pair - 如何为元素编写比较器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!