How do I pass in / use a vector <T> vect
in sort()
function ?
Thanks for the help.
I have a few classes:
Class A {
int x;
int getX() {return x;}
}
Class B : public A {
int x;
}
and a few vectors :
vector< A > a_vector;
vector< B > b_vector;
and I would like to call sortByX
for these 2 classes
template <typename T>
void sortByX(const vector<T> &vectorName, int num)
{
switch (num)
{
// Sort In Ascending
case 0:
sort(vectorName.begin(), vectorName.end(), sortByX_ascending);
break;
// Sort In Descending
case 1:
sort(vectorName.begin(), vectorName.end(), sortByX_descending);
break;
}
}
Below are the comparator functions:
bool sortByX_ascending(const A &lhs, const A &rhs) { return lhs.getX() < rhs.getX(); }
bool sortByX_descending(const A &lhs, const A &rhs) { return lhs.getX() > rhs.getX(); }
and when I invoke
sortByX(a_vector, 0);
I got an error
/Library/Developer/CommandLineTools/usr/include/c++/v1/algorithm:4016:17: error: no matching function for call to 'swap'
swap(*__first, *__last);
^~~~
/Library/Developer/CommandLineTools/usr/include/c++/v1/algorithm:4201:5: note: in instantiation of function template specialization 'std::__1::__sort<bool (*&)(const A &, const A
&), const A *>' requested here
__sort<_Comp_ref>(__first, __last, __comp);
Aucun commentaire:
Enregistrer un commentaire