结构体用于STL容器

结构体用于泛型编程时,要重载小于运算符,STL里的容器都是有默认排序的,STL中的排序都是默认使用小于号来排序。因此,在对结构体排序时,我们就需要重载小于号!

struct Currency{
	string symbol;
	int coins;

	//重载小于号
	bool operator <(const Currency &A) const
	{
	  int com = symbol.compare(A.symbol);
	  if (com < 0) return true;  //先比较symbol
	  if (com == 0) return coins<A.coins?true:false;   //symbol相同时,再比较coins
	  return false;
	}

	//重载==操作符
	bool operator==(const Currency &A) const
	{
		if(symbol == A.symbol && coins == A.coins)
		{
			return true;
		}
		return false;
	}
	friend ostream& operator<<(ostream &out,Currency currency);//流运算符只能定义为友元函数或普通函数,而不能定义为成员函数
};

//重载IO输出操作
ostream& operator<<(ostream &out,Currency currency)
{
	out<<"the symbol is "<<currency.symbol<<",the coins are "<<currency.coins<<endl;
	return out;
}

主函数:
map<Currency,string> smap;
	Currency value1;
	value1.symbol = "usa";
	value1.coins = 10;
	smap.insert(map<Currency,string>::value_type(value1,"abc"));

	Currency value2;
	value2.symbol = "usa";
	value2.coins = 10;
	if(value1 == value2)
	{
		cout<<"the same"<<endl;
	}
	smap.insert(map<Currency,string>::value_type(value2,"123"));

	for(map<Currency,string>::iterator iter = smap.begin();iter != smap.end(); ++iter)
	{
		cout<<iter->first<<"\t"<<iter->second<<endl;
	}

结构体作为map的key,可以将结构体转换为string,用法如下:

string strkey((const char *)&key, sizeof(key));

key是结构体,转化为变量strkey

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值