sorting in std::map where key is a std::string

后端 未结 4 1478
-上瘾入骨i
-上瘾入骨i 2021-02-01 18:20

I have a std::map mymap

Now, if I insert values in the map like:

std::map  mymap;
mymap[\"first\"] = \"hi\";
mymap[\"third\"] = \"         


        
4条回答
  •  难免孤独
    2021-02-01 19:08

    The elements in std::map are ordered (by default) by operator< applied to the key.

    The code you posted, with minor edits, worked for me as you expected:

    std::map  mymap;
    mymap["first"]="hi";
    mymap["third"]="how r you";
    mymap["second"]="hello";
    
    for (std::map::iterator i = mymap.begin(); i != mymap.end(); i++)
    {
        cout << i->second << "\n";
    }
    

    Prints:

    hi
    hello
    how r you
    

提交回复
热议问题