Reputation: 114
May I know how to use the stl::list::sort
function with an external function for abstract data types?
A sample code of the constructor is shown below:
ADType::ADType(string name, int object){
//constructor code
}
And for the methods:
using <list>
using namespace std;
bool compare_Object(ADType& first, ADType& second){
//search algorithm
return true;
}
int main(){
ADType test1 = ADType("Test 1", 123);
ADType test2 = ADType("Test 3", 142);
ADType test3 = ADType("Test 2", 200);
list<ADType> testlist;
testlist.push_back(test1);
testlist.push_back(test2);
testlist.push_back(test3);
testlist.sort(compare_Object);
//code to print out objects in list
}
The above line gave me both the error C3867 for function call missing argument list and C2660 for the function not taking the argument. Is there something wrong with the code I have just posted?
Upvotes: 0
Views: 262
Reputation: 543
A simpler fix would be implementing the compare method as a static method so no object instances is needed to use the method.
static bool compare_Object(BaseObj& first, BaseObj& second){
return first.getLength() > second.getLength();
// return true give me error since it can't really sort.
}
BaseObj class:
BaseObj::BaseObj(int a) {
length = a;
}
int BaseObj::getLength() {
return length;
}
Upvotes: 0
Reputation:
Your sample code has some issues (incomplete, possible slicing, not const correct) and does not show any polymorphism.
In C++11 you might do:
#include <iostream>
#include <memory>
#include <list>
struct A {
virtual ~A() {}
virtual void print() const { std::cout << "A\n"; }
};
struct B : A {
virtual void print() const { std::cout << "B\n"; }
};
inline bool operator < (const A& a, const A& b) {
return dynamic_cast<const A*>(&a) && dynamic_cast<const B*>(&b);
}
template <typename T>
inline bool less_unique_ptr(const std::unique_ptr<A>& a, const std::unique_ptr<A>& b) {
return *a < *b;
}
int main (int argc, char *argv[])
{
std::list<std::unique_ptr<A>> ptr_list;
ptr_list.emplace_back(new B);
ptr_list.emplace_back(new B);
ptr_list.emplace_back(new A);
ptr_list.sort(less_unique_ptr<A>);
for(const auto& e : ptr_list)
e->print();
return 0;
}
Upvotes: 1