当map存放结构体、类时,会报错:
这是因为map内部有序,有排序机制,所以要定个规则使它有序,所以需要重载operator < 运算符函数
比如(类同理):
struct solution {
int x, y;
solution() {}
solution(int x1, int y1) :x(x1), y(y1) {}
bool operator<(const solution& s) const {
return x < s.x;
}
};
但如上的例子是基于x进行比较的,故如果两个结构体的x值是一样的,那么map的size是不会改变的
#include<iostream>
#include<map>
using namespace std;
struct solution {
int x, y;
solution() {}
solution(int x1, int y1) :x(x1), y(y1) {}
bool operator<(const solution& s) const {
return x < s.x;
}
};
int main() {
map<solution, int> m;
m[solution(1, 2)] = 6;
m[solution(1, 3)] = 7;
cout << m[solution(1, 2)] << endl;
cout << m[solution(1, 3)] << endl;
cout << m.size() << endl;
}
此段代码输出的是
7
7
1
也就是说,m[solution(1, 3)] = 7时,m[solution(1,2)]被更新为7,map的size不变
如果两个结构体的x值不同,则map的size是会改变的
map<solution, int> m;
m[solution(1, 2)] = 6;
m[solution(4, 2)] = 7;
cout << m[solution(1, 2)] << endl;
cout << m[solution(4, 2)] << endl;
cout << m.size() << endl;
输出的是
6
7
2