# Mapping a vector to specific range

• A+
Category：Languages

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?

Using a helper vector of pairs:

``std::vector<int> a { -6, -7, 1, 2 };  std::vector<std::pair<int, int>> tmp; for (int i = 0; i < (int) a.size(); ++i) {     tmp.push_back({ a[i], i }); }  std::sort(tmp.begin(), tmp.end());  std::vector<int> b; for (auto & x : tmp) {     b.push_back(x.second + 1); } ``

Demo

Using a helper priority_queue of pairs (to avoid explicit sorting):

``std::vector<int> a { -6, -7, 1, 2 };  std::priority_queue<std::pair<int, int>> tmp; for (std::size_t i = 0; i < a.size(); ++i) {     tmp.push({ -a[i], i}); }  std::vector<int> b; do {     b.push_back(tmp.top().second + 1); } while (tmp.pop(), !tmp.empty()); ``

Demo