Sorting a std::vector> by the string?

后端 未结 4 1292
猫巷女王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:32

    Answer to "duplicate question" of this: link: Sort a vector of pairs by first element then by second element of the pair in C++?

    bool cmp(const pair<int,int>&x,const pair<int,int>y){
    if(x.first==y.first){
       return(x.second<y.second);
    }
    return(x.first<y.first);
    }
    
    array of pairs before:
    5 2
    4 2
    8 2
    8 3
    8 1
    array of pairs after:
    4 2
    5 2
    8 1
    8 2
    8 3
    
    0 讨论(0)
  • 2020-11-28 15:52

    You can use a custom comparator to order on the pairs' .first only.

    sort(begin, end,
         compose2(less<string>(),
                  select1st<pair<string, bool> >(),
                  select1st<pair<string, bool> >()));
    
    0 讨论(0)
  • 2020-11-28 15:57
    std::vector<std::pair<std::string, bool> > v;
    std::sort(v.begin(), v.end());
    

    std::pair overloads operator< to sort first by the first element then by the second element. Thus, if you just sort the vector using the default sort ordering (operator<), you'll get your desired ordering.

    0 讨论(0)
  • 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<std::string, bool> myMap(v.begin(), v.end());
    

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

    std::multimap<std::string, bool> 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.

    0 讨论(0)
提交回复
热议问题