c++用结构体struct作为map的key时的注意点

  • Post author:
  • Post category:其他


今天发现一个新的知识盲点,做个记录。

当我们使用struct作为map的key时,我们的struct里就必须自己实现,重载 < 运算符的代码,不然就会报编译错误(除非你不用这个map,那还定义他干嘛)。为啥必须要重载实现一遍这个 < 运算呢?因为map本身是通过默认的 < 运算来对key进行排序的,现在我们用struct作为key之后,默认的这个 < 运算已经无法正确的比较出两个结构体对象的大小关系了,所以就必须我们自己实现一遍,至于两个结构体的大小该怎么比较就看您自己的需求了,我放一段示例作为参考。

struct port_spec {
    int portno;
    std::string proto;

    /* Sort in the usual nmap-services order. */
    bool operator<(const port_spec& other) const {
        if (this->portno < other.portno)
            return true;
        else if (this->portno > other.portno)
            return false;
        else
            return this->proto < other.proto;
    }
};



版权声明:本文为gaga392464782原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。