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

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

Patricia Arquette
Release: 2024-12-14 15:50:11
Original
474 people have browsed it

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

Sorting Vectors Based on Values from Another Vector

Consider a scenario where you have multiple vectors of the same length and need to sort one of the vectors while maintaining the same sorting order across all the other vectors. This might be useful when the sorted values serve as references for the elements in the other vectors.

In the provided code snippet, we have two vectors: Index and Values. Index contains integers denoting the desired sorting order, and Values contains strings that will be sorted accordingly.

One approach is to create a vector of pairs that combines the elements of Index and Values, and then sort this vector using a custom comparator. Here's how you would do it:

using myiter = std::vector<int>::const_iterator;

std::vector<std::pair<size_t, myiter>> order(Index.size());

size_t n = 0;
for (const auto& it : Index) {
    order[n++] = std::make_pair(n, it);
}

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

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

The order vector now contains the elements from Index and Values in the sorted order. You can use this to sort the other vectors as well. Here's a function template that does that:

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

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

    return ret;
}
Copy after login

Using this function, you can now obtain the sorted version of Values based on the order specified by Index:

std::vector<std::string> sortedValues = sort_from_ref(Values, order);
Copy after login

This approach allows you to efficiently sort multiple vectors in a consistent manner without the need for complex and iterative solutions.

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