Search
 
SCRIPT & CODE EXAMPLE
 

CPP

c++ sorting and keeping track of indexes

#include <iostream>
#include <vector>
#include <numeric>      // std::iota
#include <algorithm>    // std::sort, std::stable_sort

using namespace std;

template <typename T>
vector<size_t> sort_indexes(const vector<T> &v) {

  // initialize original index locations
  vector<size_t> idx(v.size());
  iota(idx.begin(), idx.end(), 0);

  // sort indexes based on comparing values in v
  // using std::stable_sort instead of std::sort
  // to avoid unnecessary index re-orderings
  // when v contains elements of equal values 
  stable_sort(idx.begin(), idx.end(),
       [&v](size_t i1, size_t i2) {return v[i1] < v[i2];});

  return idx;
}
Comment

PREVIOUS NEXT
Code Example
Cpp :: string c++ 
Cpp :: runtime 
Cpp :: split string in c++ 
Cpp :: first and last digit of a number in c++ 
Cpp :: c++ string to char* 
Cpp :: find factorial in c++ using class 
Cpp :: count c++ 
Cpp :: remove linked list elements leetcode 
Cpp :: minimum or maximum in array c++ 
Cpp :: hashset in cpp 
Cpp :: A Program to check if strings are rotations of each other or not 
Cpp :: sort an array in c++ 
Cpp :: operator overloading c++ 
Cpp :: remove elements from vector 
Cpp :: map of maps c++ 
Cpp :: ue4 endoverlap c++ 
Cpp :: InstallUtil.exe ConsoleApp 
Cpp :: heapsort 
Cpp :: how to scan vector in c++ 
Cpp :: Bit Tricks for Competitive Programming c ++ 
Cpp :: sort array in descending order c++ 
Cpp :: the number of ones int bitset 
Cpp :: print float up to 3 decimal places in c++ 
Cpp :: coin change top-down 
Cpp :: c++ over load oprator to print variable of clas 
Cpp :: Check whether K-th bit is set or not c++ 
Cpp :: variadic template constructor matches better than copy constructor 
Cpp :: get shape of eigen matrix 
Cpp :: command loop ctrl D c++ 
Cpp :: how to check private messages on reddit 
ADD CONTENT
Topic
Content
Source link
Name
9+3 =