I have a standard vector contains, for example, the following elements
[-6, -7, 1, 2]
I need to map these elements to the range from 1 to 4. i.e I need the vector to be like this
[2, 1, 3, 4]
Note that: the smallest value in the first vector (-7) was mapped to the smallest value in the second vector (1). How can I achieve that with STL?
Map of Vectors in STL: Map of Vectors can be very efficient in designing complex data structures. Syntax: map<key, vector<datatype>> map_of_vector; OR map<vector<datatype>, key> map_of_vector; For example: Consider a simple problem where we have to check if a vector is visited or not.
In C++ we can use arrays or vector as a key against to a int value like: map<vector<int> ,int > m; Can I do same in MATLAB by containers.
With range-v3:
std::vector<int> v{-6, -7, 1, 2};
auto res = ranges::view::ints(1, 1 + (int)v.size()) | ranges::to_vector;
ranges::sort(ranges::view::zip(v, res));
Demo
With just the standard library as it exists in C++17 (or really, C++11), you make a vector of indices and sort it - using itself as a projection:
vector<int> idxs(values.size());
iota(idxs.begin(), idxs.end(), 1);
sort(idxs.begin(), idxs.end(), [&](int i, int j){
return values[i-1] < values[j-1];
});
A different way of generating the indices would be to use generate_n
:
vector<int> idxs;
generate_n(back_inserter(idxs),
values.size(),
[cnt=1]() mutable { return cnt++; });
// same sort()
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