c++ - std::set with std::pair - 如何为元素编写比较器

标签 c++ opencv c++11 stl set

我有一个 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/

相关文章:

c++ - C/C++ 运行时库和 C/C++ 标准库的区别

c++ - 错误/var/tmp/kdecache 由 uid 1000 而不是 uid 0 拥有

c++ - OPENCV3 detectAndCompute 中的调试断言失败

opencv - 在 opencv 中创建复选框/按钮

c++ - std::set 在使用 std::set.erase 后包含重复元素

c++ - 如何将函数静态应用于非类型模板包的各个元素并对结果求和?

c++ - 专门化变量模板函数的问题

c++ - 可移植地链接外部库?

python - 斜线的形态闭合

c++ - 在 constexpr 中使用 strcmp 的编译器差异