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
Release: 2024-12-29 20:04:14
Original
682 people have browsed it

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());
Copy after login

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;
}
Copy after login

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template