Napalidon
Napalidon

Reputation: 137

How to return a value in a vector by reference?

I am trying to return a Vertex &, here's the code:

Vertex& Graph::getVertex(std::string v) {         // gets the vertex 
     for (std::vector<Vertex>::iterator it = vertices.begin(); it != vertices.end(); it++) {
        if ((it->getName()).compare(v) == 0)
          return it;  // if strings are the same return vertex
     }
     exit(1);
}

The problem is that getVertex is flagged as incompatible and it in the return is flagged as a reference of type Vertex & (non-const qualified) cannot be initialized with a value with of type std::vector ... How would I fix these errors?

Upvotes: 1

Views: 154

Answers (1)

Nicol Bolas
Nicol Bolas

Reputation: 474386

You're trying to return the iterator, not what the iterator points to. So you need to return *it.

Upvotes: 7

Related Questions