"<" Implementierung bei structs
-
Hallo,
ich habe den struct koord erstellt und würde gerne eine < Operation implementieren, um einen vector<koord> sortieren zu können:
struct Koord
{
Koord(int x, int y){
int m= x;
int n= y;
}
int m,n;
};es soll gelten:
Koord k1 < Koord k2, wenn k1.m < k2.m gilt!ich schätze mal, dass es keine große sache ist, aber bei solchen allgemeingültigen OPerationen harpert es bei mir...
txp4help!
:xmas1: :xmas1:
-
Nabend,
du koenntest es z. B. so machen:
struct Koord { Koord(int x, int y){ m= x; n= y; } bool lt(const Koord& k) { return m < k.m; } int m,n; }; bool operator<(const Koord& left, const Koord& right) { return left.lt(right); }mfg
v R
-
Hallo,
struct Koord {
Koord(int x, int y){
m= x;
n= y;
}bool lt(const Koord& k) {
return m < k.m;
}int m,n;
};bool operator<(const Koord& left, const Koord& right) {
return left.lt(right); // <-- FEHLER
}folgender Fehler tritt auf:
53 ... passing `const Koord' as `this' argument of `bool Koord::lt(const Koord&)' discards qualifiers
-
bool lt(const Koord& k) const {
return m < k.m;
}
-
das nimmt er mir auch nicht an. (was soll m sein?!?)
PS ich nutze Dev-C++
-
n4p
struct Koord {
Koord(int x, int y){
m= x;
n= y;
}bool lt(const Koord& k) const {
return m < k.m;
}int m,n;
};
-
klappt!!
danke!
-
Bist du sicher, dass du nur die eine Bedingung willst?
Damit sind alle Koord mit gleichem m Wert äquivalent, obwohl sie verschiedene n Werte haben.
Ich würde es so machen:
class Koord { ... bool operator < (Koord const & other) const { if (m != other.m) return n < other.n; return m < other.m; } ... };
-
Verdammt...ich vergesse das const immer wieder dahinter, sry, aber z. Glueck gibt es genug
faehige Leute hier
mfg
v R