Help about sorting vectors with custom comparator
Dear all,
I am trying to sort a vector of object by using std::sort in combination wigh my own comparator.
I have tried the following code, which does not compile, and I do not understand why.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
|
#include<stdio.h>
#include<vector>
#include<algorithm>
template<class T>
class component
{
public:
int number;
T value;
component(int n, T v) : number(n), value(v) {}
};
template<class T>
class compare
{
public:
compare(){};
bool operator() (const component<T>& c1, const component<T>& c2)
{
return (c1.value < c2.value);
}
};
int main()
{
std::vector<component<float> > v;
v.push_back(component<float>(22, 5.2));
v.push_back(component<float>(18, 3.2));
v.push_back(component<float>(22, 5.9));
v.push_back(component<float>(18, 3.6));
//this is the line that does not compile
std::sort(v.begin(), v.end(), compare<float>);
return 0;
}
|
Th error message I get is this: "expected primary-expression before ')' token". What is a primary expression?
I thank you all,
Panecasareccio.
You need to instantiate your functors.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
int main()
{
std::vector<component<float> > v;
v.push_back(component<float>(22, 5.2));
v.push_back(component<float>(18, 3.2));
v.push_back(component<float>(22, 5.9));
v.push_back(component<float>(18, 3.6));
// compare<float> cf_functor;
//std::sort(v.begin(), v.end(), cf_functor);
std::sort(v.begin(), v.end(), compare<float>());
/*
for (const component<float> &c: v)
std::cout << c.number << ' ' << c.value << '\n';
std::cout << std::endl;
*/
return 0;
}
|
The sorting needs an actual object or function to use. As you can see this is the syntax for providing a custom compare method:
http://en.cppreference.com/w/cpp/algorithm/sort
1 2
|
template< class RandomIt, class Compare >
void sort( RandomIt first, RandomIt last, Compare comp );
|
In your code you have tried to call sort that has these parameters:
1 2
|
template< class RandomIt, class Compare >
void sort( RandomIt first, RandomIt last, Compare );
|
Which is what is causing compiler errors
Topic archived. No new replies allowed.