C++, Sort One Vector Based On Another One

前端 未结 7 732
粉色の甜心
粉色の甜心 2020-12-01 21:25

The best example I\'ve got is that I want to sort Names based on their Score.

vector  Names {\"Karl\", \"Martin\", \"Paul\", \"Jennie\"};
vecto         


        
7条回答
  •  悲&欢浪女
    2020-12-01 21:34

    One way you could do this would be to store the Names and Scores in a single data structure such as a std::vector> and then sorting can be done as follows:

    #include 
    #include 
    #include 
    #include 
    //...
    std::vector> names_scores_vec;
    // ... populate names_scores_vec...
    // lambda for sorting, change to > for descending order
    auto sort_by_scores = [](const std::pair& _lhs, 
        const std::pair& _rhs) { return _lhs.second < _rhs.second; };
    std::sort(names_scores_vec.begin(), names_scores_vec.end(), sort_by_scores);
    

    Alternatively, use storage such as a std::map or std::multimap if you want repeated keys (i.e. repeated names allowed).

提交回复
热议问题