简体   繁体   中英

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

So , i have made a graph using adjacency list , and i am trying to search it by using recursion. Got an awkward error message saying 'no match for operator []'. Here's the code:

#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);
}

The variable it is an iterator.

vector <int> :: iterator it;

This can not be used to index into an array like this:

search(v,v[node][it]); // Expecting an index not an iterator.

I think what you want is to de-reference the iterator.

search(v, *it);

You have to check if the node is not out of bounds.

Try this:

#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;
}

In your code, v is a pointer (Which represents an array) to a vector. To access the subscript operator, you have to access the C Style Array first using v[first_index] . Then you have to index whatever returned object you get from the first indexing. However, you shouldn't even be using pointers for vectors. If you want to modify a container, then pass it by reference. If you want to store an array of vectors, then I recommend that you just nest them (Although this may be bad for memory, so you can create a 1D vector and compute indices).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM