Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ invalid operand to binary expression on xcode

I'm still kind of new to C++ and I just can't figure out how to fix the error. Error I'm getings is saying "Invalid operands to binary expression". Does anyone have any idea on how to fix this? Any help is appreciated!! I'm using Xcode 4.5.2. Thanks!

[Edit] OK. I've updated the code below. I'm still getting the same error at the same line (find())... but here are the changes...

Vertex myVertex = new Vertex(1); 

to

Vertex myVertex(1);

And added operator overload for <

struct Vertex {
    int node;
    bool known;
    float distance;
    Vertex *path;

    Vertex(int n=0, bool known=false, duuble dist=INFINITY):
    node(n), known(known), distance(dist) {}
};


struct Edge {
    Vertex target;
    float weight;
    bool directed;

    Edge(Vertex v2, float w, bool dir):target(v2), weight(w), directed(dir) {}
};

class Graph {
public:
    /*unrelated members are removed*/

    void findVertex() {
        Vertex myVertex(1);
        map<Vertex, vector<Edge> >::iterator itr;
        itr = edges.find(myVertex); // <--- this is the line the error seems to related to
    }

    friend bool operator< (const Vertex& lhs, const Vertex& rhs) {
        return lhs.node < rhs.node;
    }



private:
    /*unrelated members are removed*/
    vector<Vertex> vertices;
    map<Vertex, vector<Edge> > edges;
};
like image 321
selina Avatar asked Sep 28 '26 22:09

selina


2 Answers

The elements in the map are sorted from lower to higher key value following a specific strict weak ordering criterion set on construction.

You need to provide operator< for Vertex, for example:

bool operator<(const Vertex& lhs, const Vertex& rhs){
      return lhs.node < rhs.node;
  }

Also Vertex myVertex = *new Vertex(1); leaks memory as David and selbie mentioned. Have a look at this link: Why does the use of 'new' cause memory leaks?

change Vertex myVertex = *new Vertex(1); to Vertex myVertex = Vertex(1);

like image 61
billz Avatar answered Oct 01 '26 17:10

billz


I have the same problem, finally, I just change the Xcode default C++ library to libstdc++(GNU C++ standard library) in the Build Settings. And it's solved.

Just like the picture below. enter image description here

like image 31
SamSam Avatar answered Oct 01 '26 17:10

SamSam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!