排序在STL中的顺序并设置 [英] Sort Order in STL map and set
问题描述
用户定义的对象如何在map和set中排序?
据我所知,map / set是Sorted关联容器:插入的元素根据它所包含的键排序。
How are the user defined objects sorted in map and set? As far as I know, map/set are Sorted Associative Containers: the elements being inserted are sorted based on the key that it holds.
但是map和
在SGI网站上,我有以下示例:
From the SGI site, I have the following examples:
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;
}
在上面的例子中,值是如何排序的?
In the above example, how are the values sorted?
编辑:从注释中移除代码:
Code moved from comment:
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;
}
如何对值进行排序?
推荐答案
std :: map
使用函子对元素进行排序。默认情况下是 std :: less< Key>
,它使用运算符<
。在你的示例中有一个用户定义的函数 ltstr
,这将有助于根据字母顺序的按键对元素进行排序。
std::map
uses a functor to sort elements. By default is it std::less<Key>
which uses operator<
. In your sample there is an user defined functor ltstr
which will help to sort elements according to its keys in alphabetical order.
这篇关于排序在STL中的顺序并设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!