跳到正文

个人记录

注意事项

面条小王子约 2 分钟
原文

这是 2025年11月1日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2025年10月29日
收录
2025年12月12日
更新
2026年11月14日
篇幅
约 2 分钟

版本

  1. v3当前
  2. v2
  3. v1

关于set/map存结构体

重载运算符写完整

这段代码输出 11

C++
struct node
{
	int cnt, id;
	bool operator< (const node &t)const
	{
		return cnt > t.cnt;
	}
};
set<node> tong;

int main()
{
	tong.insert({1, 5});
	tong.insert({1, 6});
	cout << tong.size();
	return 0;
}

这段代码输出 22

C++
struct node
{
	int cnt, id;
	bool operator< (const node &t)const
	{
		if (cnt == t.cnt) return id > t.id;
		return cnt > t.cnt;
	}
};
set<node> tong;

int main()
{
	tong.insert({1, 5});
	tong.insert({1, 6});
	cout << tong.size();
	return 0;
}

这段代码输出 11

C++
struct node
{
	int cnt, id;
	bool operator< (const node &t)const
	{
		return cnt > t.cnt;
	}
};
map<node, int> tong;

int main()
{
	tong[{1, 5}] = 1;
	cout << tong[{1, 6}];
	return 0;
}

这段代码输出 00

C++
struct node
{
	int cnt, id;
	bool operator< (const node &t)const
	{
		if (cnt == t.cnt) return id > t.id;
		return cnt > t.cnt;
	}
};
map<node, int> tong;

int main()
{
	tong[{1, 5}] = 1;
	cout << tong[{1, 6}];
	return 0;
}