用户定义的对象如何在地图和集合中排序? 据我所知,map/set是Sorted Associative Containers:被插入的元素是根据它所拥有的键来排序的。在STL地图中排序顺序并设置
但映射和设置内部使用operator >
排序其元素。
从SGI的网站,我有以下的例子:
struct ltstr
{
bool operator()(const char* s1, const char* s2) const
{
return strcmp(s1, s2) < 0;
}
};
int main()
{
map<const char*, int, ltstr> months;
months["january"] = 31;
months["february"] = 28;
months["march"] = 31;
months["april"] = 30;
months["may"] = 31;
months["june"] = 30;
months["july"] = 31;
months["august"] = 31;
months["september"] = 30;
months["october"] = 31;
months["november"] = 30;
months["december"] = 31;
cout << "june -> " << months["june"] << endl;
map<const char*, int, ltstr>::iterator cur = months.find("june");
map<const char*, int, ltstr>::iterator prev = cur;
map<const char*, int, ltstr>::iterator next = cur;
++next;
--prev;
cout << "Previous (in alphabetical order) is " << (*prev).first << endl;
cout << "Next (in alphabetical order) is " << (*next).first << endl;
}
在上面的例子中,怎么也值进行排序?
编辑:代码从评论感动:
typedef map <string, int> Mint ;
int main()
{
string Name ;
int Marks;
Mint Grade;
for (int i = 0; i<4; i++)
{
cin>> Name ;
cin >> Marks;
Grade [Name] = Marks ;
}
Mint :: iterator iter;
for(iter = Grade.begin(); iter != Grade.end(); iter++)
cout<< (*iter).first<<“ \t ” <<(*iter).second<<“\n” ;
return 0;
}
将如何得到的值进行排序?
所以基本上map使用一个键来排序基于std :: less的值,它使用了operator
ronan
2010-07-30 09:51:09
是的,如果你没有明确地指定模板参数,它最后使用'operator <'。 – 2010-07-30 10:01:01
@Kirill它使用比较器比较键而不是元素。 – DumbCoder 2010-07-30 10:13:12