Problem mit 'sort' Algorithmus



  • Hallo,

    kann mir jemand sagen wie ich folgenden Code richtig machen muss:

    /* including header files and define classes */
    
    bool sorting(MyClass* &obj1, MyClass* &obj2) {
        return obj1->value > obj2->value;
    }
    
    int main() {
    
        std::list<MyClass*> List;
    
        /* adding objects */
    
        List.sort(sorting); // Funktioniert leider nicht :-(
    
        return 0;
    }
    


  • So?

    std::sort(List.begin(), List.end(), sorting);
    


  • Nein das ist nicht das Hauptproblem. Ich hab`s jetzt oben so geschrieben das es auch ohne 'std::' gehen müsste. Aber der Compiler meckert: 'not maching function for call to ... unknown type'



  • Habe dein Programm per copy&paste eingefügt und es funktioniert (habe natürlich Header + Klasse + sonstiges hinzugefügt) hier:

    #include <list>
    
    struct MyClass
    {
    	MyClass(int value = 0) : value(value) 
    	{ }
    	int value;
    };
    
    bool sorting(MyClass* &obj1, MyClass* &obj2) 
    { 
        return obj1->value > obj2->value; 
    } 
    
    int main() { 
    
        std::list <MyClass*> List; 
    
    	List.push_back(new MyClass(5));
    	List.push_back(new MyClass(3));
    	List.push_back(new MyClass(4));
    
        List.sort(sorting); 
    
    	for (std::list <MyClass*> ::const_iterator iter = List.begin();
    		iter != List.end(); ++iter)
    	{
    		delete *iter;
    	}
    
        return 0; 
    }
    

    Wobei ich const-correctness noch beachten würde:

    bool sorting(MyClass const* const& obj1, MyClass const* const& obj2)
    

    Gruß
    Don06



  • Okay danke, jetzt funktionierts bei mir auch 😃

    Aber noch ne andere Frage: wird das Program schnell langsam wenn man ca. 100 Objekte in einem Spiel sortiert? Ich mache das nämlich in jedem 'Frame'



  • nimm doch gleich ein std::set


Anmelden zum Antworten