Home >Backend Development >C++ >How to Sort Multiple Vectors Simultaneously Based on a Reference Vector?

How to Sort Multiple Vectors Simultaneously Based on a Reference Vector?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-03 18:16:43280browse

How to Sort Multiple Vectors Simultaneously Based on a Reference Vector?

Sorting Vectors Based on an External Reference Vector

In situations where multiple vectors of equal length are present, sorting one vector requires a solution that simultaneously transforms all other vectors accordingly.

Consider the following scenario:

std::vector<int> Index = { 3, 1, 2 };
std::vector<std::string> Values = { "Third", "First", "Second" };

Transformation: Index is sorted.

Expected Outcome: Values should be sorted as well.

One approach involves creating a vector containing both the original index and the elements from the sorting-dictating 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);

Next, this vector is sorted:

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

The sorted order allows for the rearrangement of 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;
}

The above is the detailed content of How to Sort Multiple Vectors Simultaneously Based on a Reference 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