我想用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)
是的,你需要一种比较elements(operator<
)的方法来使用std :: map.map的一个特性是它以排序顺序保存其内容,但要实现这一点,需要知道如何比较项目.
您有三种方法可以实现比较方法:
operator<
在K中添加定义创建一个comp
知道如何比较两个K元素并将其添加为模板参数的仿函数map<K, float, comp> m
;
struct comp {
bool operator()(const K& first, const K& second) {
/*****/
}
};
Run Code Online (Sandbox Code Playgroud)您可以为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
归档时间: |
|
查看次数: |
184 次 |
最近记录: |