Home > Backend Development > C++ > How to Sort One Vector Based on the Values of Another Vector?

How to Sort One Vector Based on the Values of Another Vector?

Barbara Streisand
Release: 2024-12-29 04:14:12
Original
818 people have browsed it

How to Sort One Vector Based on the Values of Another Vector?

Sorting a Vector by Values from a Different Vector

Consider the scenario where you have multiple vectors of equal length and aim to sort one vector based on the values from a different vector. For instance, you may have a vector Index of integers and a vector Values of strings. Sorting the Index vector should subsequently reorder the elements in the Values vector accordingly.

One effective approach is to create a vector that pairs the elements from the Index vector with their corresponding indices. This vector, order, can then be sorted using a custom ordering function that compares the elements from the Index vector. The sorted order vector captures the desired sorting order.

Using this sorting order, you can reorder the other vectors. Consider the following code snippet:

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);

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

The ordering function sorts the order vector based on the values from the Index vector. You can then use the order vector to reorder the Values vector using the following code:

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

This approach allows you to sort one vector by the values from another vector and apply the same sorting to additional vectors.

The above is the detailed content of How to Sort One Vector Based on the Values of Another 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