2016-05-21 8 views
0

Ich versuche, eine Funktion in C++ zu implementieren, die STL verwendet, die ein Objekt und einen Vektor von Objekten annimmt und True zurückgibt, wenn der Vektor das Objekt enthält, andernfalls false. Unten ist die Implementierung der Funktion:Ich versuche, eine Funktion mit dem Ergebnis wahr/falsch, wenn ein Element in den Vektor ist, aber ich bekomme einen Fehler?

bool belongs(vertex V, std::vector<vertex> &array) 
{ 
    std::vector<vertex>::iterator it; 
    it = find(array.begin(), array.end(), V); 
    if(it != array.end()) 
    { 
    return true; 
    } 
    else 
    { 
    return false; 
    } 
} 

Allerdings bin ich diesen Fehler:

invalid operands to binary expression ('vertex' and 'const vertex') 
     if (*__first == __value_) 

Was kann ich tun? Ich bin ein wenig neu in der Programmierung in STL mit objektorientierter Programmierung, so dass Ihre Hilfe erwartet wird.

Antwort

2

Das Hauptproblem ist, gibt es keine operator== für Vertex-Typ definiert (die find benötigt, um festzustellen, ob 2 vertex Instanzen identisch sind). Sie können einen wie folgt definieren:

#include <iomanip> 
#include <iostream> 
#include <vector> 
#include <algorithm> 

struct vertex 
{ 
    float a, b; 
    bool operator==(const vertex& o) const // <-- This method is what find is looking for 
    { 
     return a == o.a && b == o.b; 
    } 
}; 

bool belongs(vertex V, const std::vector<vertex>& array) 
{ 
    return find(array.begin(), array.end(), V) != array.end(); 
} 

int main() 
{ 
    std::vector<vertex> v = { { 1, 2 }, { 3, 4 } }; 
    std::cout << std::boolalpha << belongs({ 4, 5 }, v); 
    return 0; 
} 

Live on Coliru

Ich habe verkürzt auch die Umsetzung gehört, seine viel klarer:

return x; 

statt:

if (x) 
    return true; 
else 
    return false; 
+0

Ich habe eine Vertex-Klasse erstellt, was soll ich in diesem Fall tun? –

+0

@DanishAmjadAlvi Implementieren Sie den Operator == dafür, ich hatte Ihre Vertex-Klasse nicht, also habe ich eine erstellt. – Borgleader

+0

Bekam es! Ich denke, es hat funktioniert! Danke für Ihre Hilfe! –

Verwandte Themen