结构体用于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

你可能感兴趣的:(结构体用于STL容器)