如何通过引用返回向量中的值?

Nap*_*don 1 c++ reference

我想返回一个Vertex &,这是代码:

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);
}
Run Code Online (Sandbox Code Playgroud)

问题是getVertex标记为不兼容并且it在返回标记为类型的引用Vertex &(非const限定)不能使用类型的值初始化std::vector...我将如何修复这些错误?

Nic*_*las 7

你试图返回迭代器,而不是迭代器指向的那个.所以你需要回来*it.