Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 750fcc2

Browse files
Create sort_with_indices.cpp
1 parent 8eafde5 commit 750fcc2

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

‎sort_with_indices.cpp‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
#include <algorithm> // std::sort, std::stable_sort
2+
#include <iostream>
3+
#include <numeric> // std::iota
4+
#include <vector>
5+
6+
using namespace std;
7+
8+
// https://stackoverflow.com/questions/1577475/c-sorting-and-keeping-track-of-indexes
9+
10+
template <typename T>
11+
vector<size_t> sort_indexes(const vector<T>& v) {
12+
// initialize original index locations
13+
vector<size_t> idx(v.size());
14+
iota(idx.begin(), idx.end(), 0);
15+
16+
// sort indexes based on comparing values in v
17+
// using std::stable_sort instead of std::sort
18+
// to avoid unnecessary index re-orderings
19+
// when v contains elements of equal values
20+
stable_sort(idx.begin(), idx.end(),
21+
[&v](size_t i1, size_t i2) { return v[i1] < v[i2]; });
22+
23+
return idx;
24+
}
25+
26+
int main() {
27+
vector<int> v = { 4, 6, 7, 1, 3, 2, 9, 8, 7, 0, 5 };
28+
for(auto i : sort_indexes(v)) {
29+
cout << i << "th element: " << v[i] << endl;
30+
}
31+
return 0;
32+
}
33+
34+
/*
35+
9th element: 0
36+
3th element: 1
37+
5th element: 2
38+
4th element: 3
39+
0th element: 4
40+
10th element: 5
41+
1th element: 6
42+
2th element: 7
43+
8th element: 7
44+
7th element: 8
45+
6th element: 9
46+
*/

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /