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

How to return a value in a vector by reference?

本文关键字:向量 返回 何通过 引用      更新时间:2023-10-16

我正试图返回一个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);
}

问题是,返回中的getVertex被标记为不兼容,而it被标记为Vertex &类型的引用(非常量限定)无法用std::vector类型的值初始化。。。我该如何修复这些错误?

您试图返回迭代器,而不是迭代器指向的内容。因此需要返回*it