welcher operator bei set <myclass*>
-
Hi,
ich verwende ein set um zeiger auf objekte zu verwalten, weiß aber nicht welchen operator ich überladen muß. hier ein beispielcode der nicht so funktioniert wie ich erwartet hätte:
#include <stdio.h> #include <tchar.h> #include <iostream> #include <set> using namespace std; class Test { public: int operator<(const Test &rhs) {cout << " < " << endl; return true;}; int i; private: }; bool operator< (const Test& t1, const Test& t2) { cout << t1.i << " < " << t2.i << endl; return t1.i < t2.i; } int _tmain(int argc, _TCHAR* argv[]) { Test temp1, temp2; cout << "mit Zeigern" << endl; set<Test*> myset; myset.insert(&temp1); myset.insert(&temp2); cout << "mit Objekten" << endl; set<Test> myset2; myset2.insert(temp1); myset2.insert(temp2); }wo liegt mein denkfehler?
-
bool operator< (const Test *t1, const Test *t2);
-
Z2 schrieb:
bool operator< (const Test *t1, const Test *t2);Hübsch, aber leider kein C++. In C++ muss ein überladener Operator mindestens ein Argument vom Typ enum oder udt haben. Du hast hier aber zwei Zeiger.
@dust
In diesem Fall bietet sich ein Comparator-Objekt an:#include <stdio.h> #include <iostream> #include <set> using namespace std; class Test { public: int i; }; bool operator< (const Test& t1, const Test& t2) { cout << t1.i << " < " << t2.i << endl; return t1.i < t2.i; } struct DerefLess { template <class T> bool operator()(T* lhs, T* rhs) const { return *lhs < *rhs; } }; int main() { Test temp1, temp2; cout << "mit Zeigern" << endl; set<Test*, DerefLess> myset; myset.insert(&temp1); myset.insert(&temp2); }
-
Ups, wie peinlich. Kommt davon, wenn man immer nur Funktoren anstattt Funktionen verwendet

-
danke, hat mir sehr geholfen
