Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping a vector to specific range

Tags:

c++

stl

vector

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?

like image 418
sc0rp10n.my7h Avatar asked Dec 23 '18 19:12

sc0rp10n.my7h


People also ask

How do you map a vector?

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.

Can we use vector as key in map?

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.


2 Answers

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

like image 168
Jarod42 Avatar answered Oct 17 '22 09:10

Jarod42


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()
like image 41
Barry Avatar answered Oct 17 '22 09:10

Barry