我是否需要在K类上进行完整排序才能使用std :: map <K,L>

yo'*_*yo' 2 c++ class std map

可能重复:
std :: map键类必须满足哪些要求才能成为有效键?

我想用std::map我的班级到另一个班级的地图.如果我尝试以下代码,我会收到错误" undefined operator <".这是否意味着我需要课堂K上的订购才能使用map?它必须是完整的订购吗?我需要所有四个订购操作员还是>足够了?

#include <iostream>
#include <map>
#include <stdio.h>
using namespace std;

struct K {
    int i, j;

    K(int i, int j) : i(i), j(j){}

    friend bool operator==(const K& x, const K& y){ return (x.i==y.i)&&(x.j==y.j); }
    friend bool operator!=(const K& x, const K& y){ return !(x==y); }

/*  friend bool operator<(const K&x, const K&y){
        if(x.i<y.i) return true;
        if(x.i>y.i) return false;
        return x.j<y.j;
    }
    friend bool operator>(const K&x, const K&y){ return y<x; }
    friend bool operator<=(const K&x, const K&y){ return !(y<x); }
    friend bool operator>=(const K&x, const K&y){ return !(x<y); }
*/
};


int main(){
    map<K, float> m;
    m[K(1,2)]=5.4;
    if(m.find(K(1,2))!=m.end())
        cout << "Found: " << m[K(1,2)] << endl;
    else
        cout << "Not found" << endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

and*_*dre 5

是的,你需要一种比较elements(operator<)的方法来使用std :: map.map的一个特性是它以排序顺序保存其内容,但要实现这一点,需要知道如何比较项目.

您有三种方法可以实现比较方法:

  1. operator<在K中添加定义
  2. 创建一个comp知道如何比较两个K元素并将其添加为模板参数的仿函数map<K, float, comp> m;

    struct comp {
        bool operator()(const K& first, const K& second) {
            /*****/
        }
    };
    
    Run Code Online (Sandbox Code Playgroud)
  3. 您可以为K定义std :: less专门化

    template<>  struct less<K>
    {
        bool operator()(const K& first, const K& second) {
            /*****/
        }
    };
    
    Run Code Online (Sandbox Code Playgroud)

而且使用简单 map<K, float> m;

这是有效的,因为map的模板定义将compare函数设置为std :: less.

template <class Key,class T,class Compare = less,class Allocator = allocator >> class map