您的位置:首页 > 其它

结构体用于STL容器

2015-08-10 14:58 330 查看
结构体用于泛型编程时,要重载小于运算符,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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: