操作员[](STD :: vector)无匹配

no match for operator [ ] (std::vector)

本文关键字:vector 无匹配 STD 操作员      更新时间:2023-10-16

所以,我已经使用邻接列表制作了图形,并且我正在尝试使用递归搜索它。收到一条尴尬的错误消息,上面写着"不适合操作员[]'。这是代码:

#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向量并计算索引(。