c++ - 将 std::set 与自定义比较器进行比较

标签 c++ c++11 templates

我正在尝试使用std::tie实现operator<为了创建包含集合的结构图。没有模板的相同代码似乎可以工作。我从编译器收到此消息代码:

/usr/include/c++/4.8/bits/stl_algobase.h:888: error: no match for operator< (operand types are const SiPa<int, int> and const SiPa<int, int>)

if (*__first1 < *__first2)
              ^

如果我评论myMap.insert({akey, true});,一切都会编译线。

有什么提示吗?

template<class I = int, class S = int>
struct SiPa
{
    I i;
    S s;
};

template<class I = int, class S = int>
struct SiPaComparator
{
    bool operator() (const SiPa<I, S>& first, const SiPa<I, S>& second) const
    {
        return std::tie(first.i, first.s) < std::tie(second.i, second.s);
    }
};

template<class I = int, class S = int>
struct AKey
{
    typedef std::set< SiPa<I, S>, SiPaComparator<I,S> > SetType;
    SetType keySet;
    I keyI;
};

template<class I = int, class S = int>
struct AKeyComparator
{
    bool operator() (const AKey<I, S>& first, const AKey<I, S>& second) const
    {
        return std::tie(first.keySet, first.keyI) < std::tie(second.keySet, second.keyI);
    }
};

int main()
{
    AKey<int,int> akey;

    std::map<AKey<int,int>, bool, AKeyComparator<int,int>> myMap;
    myMap.insert({akey, true});
}

最佳答案

您需要为 struct SiPa 添加运算符<,std::map 需要它

template<class I = int, class S = int>
struct SiPa {
  I i;
  S s;

  bool operator<(const SiPa<I, S> &ref) {
    return i < ref.i && s < ref.s;
  }
};

关于c++ - 将 std::set 与自定义比较器进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41808347/

相关文章:

c++ - Foo** 是一个数组数组吗?

c++ - 关于函数和错误检查的 C++ 新手问题

c++ - string::size_type 真的大到可以容纳任何字符串吗?

c++ - 为什么 C++ 无法推断模板化的非类型模板参数?

c++ - 函数模板参数推导(类 vs 函数模板)

c++ - 为什么当klee执行Objectfile时sleep()函数不能工作?

c++ - 为什么 std::to_string 的实现会创建一个 4 倍于类型大小的缓冲区?

c++ - 是否有一种完全符合标准的方法可以使编译器将文件的确切(二进制)内容粘贴到源文件中?

c++ - 增强模板enable_if怎么样

javascript - 制作自动更新的 facebook 风格的时间格式