Home >Backend Development >C++ >How to Sort Multiple Vectors Based on the Values of a Single Vector?

How to Sort Multiple Vectors Based on the Values of a Single Vector?

Susan Sarandon
Susan SarandonOriginal
2024-12-29 20:04:14700browse

How to Sort Multiple Vectors Based on the Values of a Single Vector?

Sorting Vectors Based on Values from a Different Vector

Consider a scenario where you have multiple vectors of the same length, and you want to sort one vector by a specified order while applying the same permutation to the other vectors. This poses the challenge of how to leverage this sorting pattern across multiple vectors.

Solution

To sort a vector by values from a different vector, you can employ a custom sorter and employ a vector that pairs each element's index with its corresponding value in the sorting vector.

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& a, pair<size_t, myiter> const& b) {
        return *(a.second) < *(b.second);
    }
};

sort(order.begin(), order.end(), ordering());

Once you have the sorted ordering, you can utilize this as a lookup table for the new index of each element in the other vectors.

template <typename T>
vector<T> sort_from_ref(
    vector<T> const& in,
    vector<pair<size_t, myiter>> const& 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;
}

By applying this process, you can effectively sort the target vector and apply the same transformation to the corresponding elements in the other vectors.

The above is the detailed content of How to Sort Multiple Vectors Based on the Values of a Single Vector?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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