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.
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 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.
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 .
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 :
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With