在STL地图中排序顺序并设置

ron*_*nan 8 c++ stl

用户定义的对象如何在map和set中排序?据我所知,map/set是Sorted Associative Containers:插入的元素是根据它所拥有的键进行排序的.

但是map和set内部用于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;
}
Run Code Online (Sandbox Code Playgroud)

在上面的例子中,值是如何排序的?

编辑:代码从评论移开:

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; 

} 
Run Code Online (Sandbox Code Playgroud)

如何对值进行排序?

Kir*_*sky 8

std::map使用仿函数对元素进行排序.默认情况下是std::less<Key>使用它operator<.在您的示例中,有一个用户定义的函子ltstr,它将帮助按字母顺序按键对元素进行排序.