操作员[](STD :: vector)无匹配
no match for operator [ ] (std::vector)
所以,我已经使用邻接列表制作了图形,并且我正在尝试使用递归搜索它。收到一条尴尬的错误消息,上面写着"不适合操作员[]'。这是代码:
#include <iostream>
#include <vector>
using namespace std;
void search(vector <int> *v,int node)
{
if (node==4)
{
cout<<"found 4";
return;
}
vector <int> :: iterator it;
if (!v[node].empty())
{
for (it=v[node].begin() ; it!=v[node].end() ; it++)
{
search(v,v[node][it]);
}
}
}
int main()
{
vector <int> v[5];
v[1].push_back(2);
v[1].push_back(3);
v[2].push_back(4);
v[2].push_back(5);
search (v,1);
}
变量it
是迭代器。
vector <int> :: iterator it;
这不能用来索引这样的数组:
search(v,v[node][it]); // Expecting an index not an iterator.
我认为您想要的是延期迭代器。
search(v, *it);
您必须检查节点是否不超出范围。
尝试以下操作:
#include <iostream>
#include <vector>
using namespace std;
void search(vector<int> *v, int count, int node)
{
if (node == 4)
{
cout << "found 4";
return;
}
if (node < count && !v[node].empty())
{
for (auto it = v[node].begin(); it != v[node].end(); it++)
{
search(v, count, *it);
}
}
}
int main()
{
vector<int> v[5];
v[1].push_back(2);
v[1].push_back(3);
v[2].push_back(4);
v[2].push_back(5);
search(v, sizeof(v) / sizeof(v[0]), 1);
return 0;
}
在您的代码中, v
是 pointer (代表数组(向量。要访问下标运算符,您必须首先使用v[first_index]
访问C样式数组。然后,您必须索引从第一个索引中获得的任何返回的对象。但是,您甚至不应该将指针用于向量。如果要修改容器,请通过参考将其传递。如果要存储一个向量数组,我建议您只是嵌套它们(尽管这可能对内存不利,因此您可以创建1D向量并计算索引(。
相关文章:
- 从 std::vector<无符号字符>切片中提取 int?
- Rcpp并行无匹配函数,用于调用"转换"
- 如何将带有十六进制值的 std::string 转换为 std::vector<无符号字符>
- 在 std::vector<无符号字符中存储任意数据的方法>
- 运算符重载错误无匹配运算符<<
- 为什么通过带有文字编号的引用调用会出现"无匹配函数"错误?
- C++:提升 ptree 删除子项:无匹配功能
- 无匹配函数呼叫getline()
- 错误:呼叫构造器的匹配函数无匹配功能
- 将十六进制值存储到 std::vector<无符号字符中>
- C 线程 - 无匹配函数供呼叫
- C 汇编错误:无匹配的构造函数以进行初始化
- 操作员[](STD :: vector)无匹配
- 错误代码:无匹配函数供呼叫
- 错误:如果(object1 == object2),“操作器==”无匹配(操作数类型为“ const class”和“
- 为链接列表构建迭代器类(错误:无匹配的构造函数以初始化)
- 子类/超类的"无匹配函数调用"
- 无匹配函数呼叫
- C 11无匹配函数,可以呼叫'std :: vector
- [C++ STL]-pair<vector-iter,int*> - 不匹配 - 无匹配函数