简体   繁体   中英

How can I sort a vector according to a property of its values?

If I have a vector of pairs

vector<pair<int,vector<int>>> myvector;

How can I sort this vector according to nth element of its inner vector?

My previously-asked question on this topic contains the answer of sorting a vector of pairs according to a second element of the pair by using a pre-defined sorting_function() as below. However, in this case, I have no idea what the form of sorting_function() should be...

sort(v.begin(), v.end(), sorting_function());

You may re-use the comparator from my answer to your previous question; sort expects an instance of it, so pass in a temporary one:

std::sort(v.begin(), v.end(), MyComparator<1>());

So, here's the full example:

template <std::size_t N>
struct MyComparator
{
   typedef std::pair<int, std::vector<int>> value_type;
   bool operator()(const value_type& lhs, const value_type& rhs)
   {
      return lhs.second.at(N) < rhs.second.at(N);
   }
};

/**
 * A set of (int, int{2,}) pairs, sorted by the 2nd element in
 * the 2nd item of each pair.
 */
std::vector<std::pair<int, std::vector<int>>> my_data;

int main()
{
    my_data.push_back(std::make_pair(1, std::vector<int>{0,5,0,0}));
    my_data.push_back(std::make_pair(2, std::vector<int>{0,2,0,0}));
    my_data.push_back(std::make_pair(3, std::vector<int>{0,1,0,0}));
    my_data.push_back(std::make_pair(4, std::vector<int>{0,9,0,0}));

    std::sort(my_data.begin(), my_data.end(), MyComparator<1>());

    for (const auto& el : my_data)
        std::cout << el.first << ' ';
}

// Output: 3 2 1 4

( live demo )

struct comparator
{
    comparator (int n) : n(n) { }

    typedef std::pair<int, std::vector<int>> key_type;

    bool operator() (key_type const & k1, key_type const & k2)
    {
        return k1.second[n] < k2.second[n];
    }

    int n;
};

I have no idea where you want 'n' to come from, but basicly that's it. Also you should put bounds checking in it.

Then you can sort your array this way:

std::sort(v.begin(), v.end(), comparator(n));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM