I want to pass the below function as as the third argument in sort() function from C STL.
bool fn(int a, int b, vector<int> v1)
{
if (v1[a]< v1[b]) return true;
else return false;
}
I want sort a vector according to the values in another vector.
sort(v2.begin(), v2.end(),fn);
How do I pass the first vector v1
to the function fn
so that the function fn
can use it to sort the second vector v2
without the use of global variables?
CodePudding user response:
First, your comparator has the wrong signature. std::sort
expects a callable that can be called with 2 elements.
You can use a lambda expression that captures the vector:
sort(v2.begin(), v2.end(),[&v1](const auto& a,const auto& b){ return v1[a]< v1[b]; });
I tried to write this function
fn
insidemain
in hopes that it would be in scope but that didn't work.
You cannot define functions within functions. You can define a type with operator()
inside a function, and thats basically what a lambda expression does. The following hand written functor will achieve the same:
struct my_comparator {
std::vector<int>& v1;
bool operator(size_t a,size_t b) {
return v1[a] < v1[b];
}
};
std::sort(v2.begin(),v2.end(),my_comparator{v2});