Reputation: 45
How to make predicate function that counts number of iterations in sort algorithm ?
I guess I'm supposed to make a functions that returns lambda becausee of: auto p1 = predicate_with_counter(predicate1, counter);
.But I have no idea how to do it.In text of problem it says that main function should remain as it is, so changing main is not allowed
#include <vector>
#include <iostream>
#include <algorithm>
// predicate_with_counter() ???
bool predicate1(double a, double b){
return a > b;
}
int main(){
using namespace std;
size_t counter;
vector<double> v1{2,4,0,-1,5};
auto p1 = predicate_with_counter(predicate1, counter);
sort(begin(v1), end(v1), p1);
cout << "Number of comparisons in sorting of v1 : " << counter << endl;
return 0;
}
Upvotes: 1
Views: 123
Reputation: 4096
Based on the requirements discussed in the comments I will present 2 solutions. The first one does not use lambdas and will work in all versions of C++
struct predicate_with_counter {
// typedef for the function to be passed as argument
typedef bool(*predicate)(double, double);
predicate_with_counter(predicate pred, size_t& counter) :
pred_(pred), counter_(counter) {
// Initialize counter to 0 since it's uninitialized in main
counter_ = 0;
}
// Overload function call operator so it can be used in `sort`
bool operator()(double a, double b){
++counter_;
return pred_(a,b);
}
predicate pred_;
size_t& counter_;
};
The other option, using lambdas and C++14 return type deduction
auto predicate_with_counter(bool(*predicate)(double a, double b), size_t& counter) {
// Initialize counter to 0 since it's uninitialized in main
counter = 0;
return [predicate, &counter](double a, double b) {
++counter;
return predicate(a,b);
};
}
While the second option is a lot shorter it is (subjectively) harder to understand. Pick whichever one you prefer
Upvotes: 2
Reputation: 721
That's how I solved your problem using lambda expression:
#include <vector>
#include <iostream>
#include <algorithm>
int main() {
using namespace std;
size_t counter=0;
vector<double> v1{ 2,4,0,-1,5 };
sort(begin(v1), end(v1), [&counter](double a, double b)
{
counter++;
return a > b;
});
cout << "Number of comparisons in sorting of v1 : " << counter << endl;
return 0;
}
Answering your question, if you want to make it as a function, you can use auto:
auto count_comparisons = [&counter](double a, double b)
{
counter++;
return a > b;
};
sort(begin(v1), end(v1),count_comparisons );
Upvotes: 3