map 自定义结构 存储 STL

本文介绍如何通过重载比较运算符来实现自定义结构体在C++ STL map中的存储。通过示例代码展示了如何定义结构体并重载小于运算符以满足map内部排序的要求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

map如何存储自己使用的对象进行存储~~

只需要重载比较函数就可以了。例子如下


#include<stdio.h>
#include<map>
#include<string>
#include <iostream>
using namespace std;
struct node{
    int x;
    int y;

};
    bool operator < (const node & p1 ,const node & p2) //重载比较函数 重要
    {
        if(p1.y == p2.y)
            return  p1.x < p2.x;
        return p1.y < p2.y;
    }
int main()

{int n;

    map<node,int> mymap;//定义自己的map
	string s,str;
	int i;
	for(i = 0 ; i < 5 ; i++)
	{
	    node p;
	    p.x = p.y =0;
		cin>>p.x>>p.y;
		mymap[p]++; //直接使用[]就可以进行定位了
		//cout<<mymap[p]<<endl;

	}
	map<node,int>::iterator ite;
	for(ite = mymap.begin();ite != mymap.end(); ite++)
	   cout<< "x = "<<ite->first.x << "  y = "<< ite->first.y<<" "<<ite->second <<endl;

return 0;
}

而重载hash_map需要重载等于跟比较函数
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值