0

The compiler says the following error message for my simple depth first search algorithm written in C++:

error: no match for 'operator[]' (operand types are 'std::vector' and 'std::vectorstd::vector<int >::iterator {aka __gnu_cxx::__normal_iteratorstd::vector<int*, std::vectorstd::vector<int > >}') if (!visited[i])

Here is the code block:

#include<bits/stdc++.h>
...
vector<bool> visited;
vector<vector<int>> adj_matrix;
...
void dfs(int n) {
  //Possible problem
  if (!visited[n])
    visited[n] = true;
  for (vector<int> row : adj_matrix) {
    for (vector<vector<int>>::iterator i = adj_matrix.begin();
         i != adj_matrix.end(); ++i) {
      if (!visited[i])
        dfs(row[i]);
    }
  }
}

I also tried using a pointer as an array index, like so:

    if (!visited[*n])
    visited[*n] = true;

but it says the exact same thing.

Yael R
  • 13
  • 3
  • 6
    What you identify as the "problem area" is wrong. The problem is your usages of the iterator **`i`** as index. – Some programmer dude May 21 '21 at 12:05
  • 1
    Additionally: be wary of [vector](https://en.cppreference.com/w/cpp/container/vector_bool) – Aykhan Hagverdili May 21 '21 at 12:07
  • 4
    On a couple of unrelated notes, please [don't include ``](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) or [use `using namespace std;`](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice). Those are bad habits. – Some programmer dude May 21 '21 at 12:07
  • While it is not the main issue, note that `for (vector row : adj_matrix)` will make a _copy_ of each row, which is wasteful. Consider using a reference-to-const instead. – chi May 21 '21 at 12:41

1 Answers1

0

The problem is in visited[i], where i is an iterator. If you want to iterate two vectors with a common index, then use directly a int or size_t, because iterators belong to a single container (in this case, to adj_matrix, not to visited) and behave like pointers, not like indexes.

So replace your last piece of code with this:

for (vector<int> row : adj_matrix) {
    for (int i = 0; i != adj_matrix.size(); ++i) {
      if (!visited[i])
        dfs(row[i]);
    }
}
Miguel
  • 2,130
  • 1
  • 11
  • 26