C++ STL映射和集合中的排序顺序
用户定义的对象如何在地图和集合中排序? 据我所知,map/set是排序关联容器:插入的元素是根据它所持有的键排序的 但是映射和设置内部使用C++ STL映射和集合中的排序顺序,c++,stl,C++,Stl,用户定义的对象如何在地图和集合中排序? 据我所知,map/set是排序关联容器:插入的元素是根据它所持有的键排序的 但是映射和设置内部使用操作符>对元素进行排序 从SGI站点,我有以下示例: struct ltstr { bool operator()(const char* s1, const char* s2) const { return strcmp(s1, s2) < 0; } }; int main() { map<con
操作符>
对元素进行排序
从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;
}
struct ltstr
{
布尔运算符()(常量字符*s1,常量字符*s2)常量
{
返回strcmp(s1,s2)<0;
}
};
int main()
{
地图月份;
月份[“一月”]=31;
月份[“二月”]=28;
月份[“三月”]=31;
月[“四月”]=30;
月[“五月”]=31;
月[“六月”]=30;
月份[“七月”]=31;
月份[“八月”]=31;
月[“9月”]=30;
月份[“十月”]=31;
月份[“11月”]=30;
月份[“12月”]=31;
cout首先,默认情况下使用的是运算符,而不是codeoperator>
。在您的情况下,在创建映射对象时,您通过传递第三个模板参数来传递自定义比较函数。将每个元素插入映射时,此比较函子用于确定对象在映射中的相对顺序map,即用于比较键。例如,当您执行月[“二月”]=28;
时,map会比较键“一月”和“二月”。由于我们正在进行字符串比较,此比较返回大于0的值。此值用于确定键“二月”相对于“一月”的位置.使用函子对元素进行排序。默认情况下,它是使用运算符的。基本上,map使用键根据std::less对值进行排序,后者使用运算符operator@Kirill它使用比较器来比较键而不是元素。@DumbCoder,元素被认为是根据这些键排序的。@ronan:将注释中的代码复制到问题中!但代码按std::less排序,它使用std::string中定义的运算符<来给出一个字典式较少的字符串(即与使用char*和ltstr时的实验相同)
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;
}