Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the sorted index of a vector?

I have a vector. It is not sorted. Now I want to get its indices which will sort the vector. For example vector<int> v{1, 3, 2}, sorted indices are {0, 2, 1} because v[0] <= v[2] <= v[1]. If two equal, doesn't matter which one go first.

like image 930
user1899020 Avatar asked Jun 09 '16 17:06

user1899020


People also ask

How to sort a vector based on its present index?

Approach: The idea is to store each element with its present index in a vector pair and then sort all the elements of the vector, Finally, print the elements with its index associated with it. Below is the implementation of the above approach:

How to find index of element in a vector in C++?

How to find index of a given element in a Vector in C++. Given a vector V consisting of N integers and an element K, the task is to find the index of element K in the vector V. If the element does not exist in vector then print -1. The index of 54 is 2, hence output is 2.

What is the index of 54 in the given vector?

The index of 54 is 2, hence output is 2. Recommended: Please try your approach on {IDE} first, before moving on to the solution. find (): Used to find the position of element in the vector. Subtract from the iterator returned from the find function, the base iterator of the vector .

How to find the position of an element in a vector?

find (): Used to find the position of element in the vector. Subtract from the iterator returned from the find function, the base iterator of the vector . Finally return the index returned by the subtraction. Below is the implementation of the above approach :


1 Answers

What you're looking for is called tag sorting (or index sorting). Here is a minimal example using lambdas in C++11:

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

template<typename T>
std::vector<std::size_t> tag_sort(const std::vector<T>& v)
{
    std::vector<std::size_t> result(v.size());
    std::iota(std::begin(result), std::end(result), 0);
    std::sort(std::begin(result), std::end(result),
            [&v](const auto & lhs, const auto & rhs)
            {
                return v[lhs] < v[rhs];
            }
    );
    return result;
}

int main()
{
    std::vector<char> v{'a', 'd', 'b', 'c'};
    auto idxs = tag_sort(v);
    for (auto && elem : idxs)
        std::cout << elem << " : " << v[elem] << std::endl;
}

Live on Coliru

like image 130
vsoftco Avatar answered Oct 13 '22 21:10

vsoftco