📜  argsort c++ (1)

📅  最后修改于: 2023-12-03 15:29:27.991000             🧑  作者: Mango

Argsort in C++

In C++, argsort is a function that returns the indices that would sort an array in ascending order. This can be useful for various algorithms such as searching, sorting, and ranking.

Syntax

The syntax for argsort in C++ is:

void argsort(const std::vector<T>& v, std::vector<size_t>& p);

Here, v is the vector to sort and p is the resulting vector of indices.

Example

Here is an example of how to use argsort in C++:

#include <iostream>
#include <vector>
#include <algorithm>

template<class T>
void argsort(const std::vector<T>& v, std::vector<size_t>& p) {
    p.resize(v.size());
    std::iota(p.begin(), p.end(), 0);
    std::sort(p.begin(), p.end(), [&v](size_t i, size_t j) { return v[i] < v[j]; });
}

int main() {
    std::vector<double> v{ 3.1, 4.5, 1.2, 6.7, 2.8 };
    std::vector<size_t> p;

    argsort(v, p);

    for (auto i : p) {
        std::cout << i << " ";
    }
    std::cout << std::endl;

    return 0;
}

In this example, we have a vector v of double values and an empty vector p. We call argsort(v, p) to obtain the indices that would sort v in ascending order. The resulting p vector is then printed to the console. The output of this program would be:

2 4 0 1 3

This indicates that the smallest value in v is at index 2, followed by the value at index 4, and so on.

Conclusion

The argsort function in C++ can be a valuable tool for sorting and ranking arrays. By using this function, you can obtain the indices that would sort an array in ascending order, allowing you to perform various algorithms with ease.