Sorting a std::vector> by the string?

后端 未结 4 1351
猫巷女王i
猫巷女王i 2020-11-28 15:25

How can I sort this vector by comparing the pair.first which is an std::string? (without providing a static compare function, nor use

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-28 15:57

    I really like James' answer, but there's one other option you might want to consider - just funnel everything into a std::map:

    std::map myMap(v.begin(), v.end());
    

    Or, if you have duplicate strings, a std::multimap:

    std::multimap myMultiMap(v.begin(), v.end());
    

    This does have the added advantage that if you then need to add or remove new key/value pairs, you can do so in O(lg n), as opposed to O(n) for the sorted vector.

    If you really must use a vector, then go with James' answer. However, if you have a vector of pairs, there's a good chance that you really want a std::map.

提交回复
热议问题