Yesterday I came across a question whereby I need to store the location and the respective element at that location and every time I need to access the location to perform the given operation here the array elements can repeat I know for some of you the doubt may be silly But i am kinda weak in data structure So please help..
Let's take a specific problem as an example. Say you're given a list of ints
43, 24, 11, 35, 52
and you want to print the indices of where the original elements go after the list gets sorted. So it would be4 2 1 3 5
in this case.What you'd do is store it in a
vector<pair<int, int>> arr
, wherearr[i].first
is the value at positioni
, andarr[i].second
is the index (i
originally, but will change after sorting).Then sort the array and print out all
arr[i].second
values.Another similar use is for permutations. It's often necessary to 'invert' them (not sure if that's correct terminology). So if you have an array
perm[i]
, you want another arrayind[i]
such thatperm[ind[i]] = i
(ind[i]
stores the index ofi
inperm
). What you do is iterate throughperm
and setind[perm[i]] = i
for all0 <= i < n
.