[Frage] STL std::find und operator==
-
Hallo Leute,
ich habe folgendes Problem und finde die Lösung nicht.
// container typedef std::vector<myclass*> class_cont; // container füllen class_cont test; // werte sind schon gesetzt ... myclass to_find; // suche nach element class_cont::iterator res = std::find (test.begin (), test.end (), to_find);
Bekomme folgende Fehlermeldung:
error C2679 Binaerer Operator '==' : Kein Operator definiert, der einen rechtsseitigen Operator vom Typ 'const class web_object' akzeptiertHabs dann mal selbst probiert
for (lass_cont::iterator it = test.begin (); it != test.end (); ++it) { // das geht ohne probleme if ((*it)->operator== (to_find)) { break; } // hier entsteht wieder der error C2679 if ((*it) == to_find) { break; } }
Der operator== ist für die Klasse myclass überladen.
Kann mir jemand das Problem (und die Lösung) erklären?
-
Schau dir mal den typen von *it an. Es ist myclass*
a->b
ist ja das selbe wie
(*a).bfolglich ist
(it)->operator== (to_find)
das selbe wie
((*it)).operator== (to_find)
und das ist das selbe wie
**it == to_findund nun vergleiche
**it == to_find
mit
*it == to_find
-
Danke sehr, habe deine Erklärung verstanden!
Kann allerdings nocht nicht die Lösung finden um std::find (test.begin (), test.end (), to_find) zu nutzen
Muss ich dazu den operator== mehrmals überladen?Danke für deine Hilfe!
-
[cpp]template<typename T>
class MyPredImpl
{
public:
MyPredImpl(const T &obj)
: obj(obj)
{
}bool operator()(const T *p) const
{
return *p == obj;
}private:
const T &obj;
};template<typename T>
MyPredImpl<T> myPred(const T &obj)
{
return MyPredImpl<T>(obj);
}...
myclass to_find;
// suche nach element
class_cont::iterator res = std::find_if (
test.begin (), test.end (), myPred(to_find)); [/cpp]