[cpp][stl][lista]problem podczas sortowania obiektów różnego typu w liscie
Ostatnio zmodyfikowano 2021-02-13 21:37
aaadam Temat założony przez niniejszego użytkownika |
[cpp][stl][lista]problem podczas sortowania obiektów różnego typu w liscie » 2021-02-13 20:15:14 hej, przeładowałem operator, dlaczego wciąż mi nie sortuje ?? #include <iostream> #include <list> #include <memory> #include <stdlib.h> using namespace std;
class Base { public: int x; Base() { x = 0; cout << "create base" << endl; } virtual void say() { cout << "say base" << this->x << endl; } virtual ~Base() { cout << "delete base" << endl; } bool operator <( const Base & Obj ) const { return x < Obj.x; } };
class A : public Base { public: A() { x = rand() % 100 + 1; cout << "create A" << endl; } void say() { cout << "say A :" << this->x << endl; } ~A() { cout << "delete A" << endl; } };
class B : public Base { public: B() { x = rand() % 100; cout << "create B" << endl; } void say() { cout << "say B :" << this->x << endl; } ~B() { cout << "delete B" << endl; } };
class C : public Base { public: C() { x = rand() % 100; cout << "create C" << endl; } void say() { cout << "say C :" << this->x << endl; } ~C() { cout << "delete C" << endl; } };
int main() { A * a = new A(); B * b = new B(); C * c = new C(); cout << "usuwanie-------------------------------------------" << endl; delete a; delete b; delete c; cout << "listy----------------------------------------------" << endl; list < unique_ptr < Base >> my_list; my_list.push_back( unique_ptr < Base >( new Base() ) ); my_list.push_back( unique_ptr < Base >( new A() ) ); my_list.push_back( unique_ptr < Base >( new B() ) ); my_list.push_back( unique_ptr < Base >( new C() ) ); cout << "podaj ilosc" << endl; int x; cin >> x; for( int i = 0; i < x; i++ ) if( rand() % 2 == 0 ) my_list.push_back( unique_ptr < Base >( new A() ) ); else if( rand() % 3 == 0 ) my_list.push_back( unique_ptr < Base >( new B() ) ); else my_list.push_back( unique_ptr < Base >( new C() ) ); cout << endl << "rozmiar listy " << my_list.size() << endl; for( auto const & i: my_list ) { i->say(); } my_list.sort(); cout << "po sortowaniu" << endl; for( auto const & i: my_list ) { i->say(); } my_list.clear(); cout << endl << "rozmiar listy po usuwaniu " << my_list.size() << endl; return 0; }
[ cpp / ]
|
|
pekfos |
» 2021-02-13 20:39:52 Używany jest operator < dla typu elementu, czyli tu dla std::unique_ptr<>. |
|
aaadam Temat założony przez niniejszego użytkownika |
» 2021-02-13 20:52:24 dałem radę tym : bool compare_by_uniqptr( const unique_ptr < Base > & a, const unique_ptr < Base > & b ) { return a->x < b->x; }
a samym operatorem da się zrobić ? Jeżeli tak to proszę o podpowiedź. |
|
pekfos |
» 2021-02-13 21:37:21 W tym wypadku nie. |
|
« 1 » |