如何通过引用返回向量中的值
How to return a value in a vector by 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);
}
问题是,返回中的getVertex
被标记为不兼容,而it
被标记为Vertex &
类型的引用(非常量限定)无法用std::vector
类型的值初始化。。。我该如何修复这些错误?
您试图返回迭代器,而不是迭代器指向的内容。因此需要返回*it
。
相关文章:
- 矩阵向量乘法(cublasDgemv)返回零
- C++中函数的向量返回类型引发错误
- 元组由 Swig 生成的 Python 包装器返回,用于C++向量
- 在 C++11 中,如何查找并返回以给定字符串开头的字符串向量中的所有项?
- 从 std<Derived>::shared_ptr 的向量返回 std::shared_ptr<Base>
- 从对象的向量返回某个类的对象
- C++ 将向量中出现 n 次的所有元素作为向量返回
- 向量返回负大小 c++
- 如何从向量返回给定类型的元素?
- 将对象的向量返回到函数
- 尝试从向量返回对象时出现"没有可行的重载运算符 [] 错误
- 调用函数时,如何通过向量返回类型
- 向量返回/加法算法的问题
- 在向量返回上移动语义行为
- 从int c++的向量返回一个无符号长
- 向量返回空 C++
- 从融合向量的std向量返回列,无需复制
- C++为空向量上的向量返回什么::back()
- 函数的向量返回
- 如何用适当的OO有效地将100万的私有向量返回给其他几个类