Home > Backend Development > C++ > How to Sort One `std::vector` Based on the Order of Another?

How to Sort One `std::vector` Based on the Order of Another?

DDD
Release: 2024-12-07 12:16:13
Original
731 people have browsed it

How to Sort One `std::vector` Based on the Order of Another?

Sorting a std::vector by Values of a Different std::vector

This problem involves aligning the ordering of a vector with the order of another vector. For instance, the vector Index contains numbers [3, 1, 2] and the vector Values contains strings "Third, First, Second." Sorting Index in ascending order ([1, 2, 3]) should result in Values being sorted in the corresponding order (["First", "Second", "Third"]).

Solution:

A common approach involves creating a vector order by combining indices from Index and their corresponding elements from Values. This vector can then be sorted using a custom comparator that compares the elements in Index:

typedef vector<int>::const_iterator myiter;
vector<pair<size_t, myiter>> order(Index.size());

size_t n = 0;
for (myiter it = Index.begin(); it != Index.end(); ++it, ++n)
    order[n] = make_pair(n, it);

struct ordering {
    bool operator ()(pair<size_t, myiter> const&amp; a, pair<size_t, myiter> const&amp; b) {
        return *(a.second) < *(b.second);
    }
};

sort(order.begin(), order.end(), ordering());
Copy after login

The resulting order vector now contains the sorted indices. To apply this order to Values, the following function can be used:

template <typename T>
vector<T> sort_from_ref(
    vector<T> const&amp; in,
    vector<pair<size_t, myiter>> const&amp; reference
) {
    vector<T> ret(in.size());

    size_t const size = in.size();
    for (size_t i = 0; i < size; ++i)
        ret[i] = in[reference[i].first];

    return ret;
}

Values = sort_from_ref(Values, order);
Copy after login

This function takes the original vector in and the reference vector containing the sorted indices and returns a copy of in sorted accordingly.

The above is the detailed content of How to Sort One `std::vector` Based on the Order of Another?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template