The following code is a naive implementation of a solution to a problem in which a 2D vector of 1's and 0's are inputted to some function closedIsland
where 1's in some column and row represent water and 0's represent land. The aim of the algorithm is to find the number of 'closed islands' which are pieces of land surrounded by water. I am using iterators to loop over the vector and I have written a helper function called checkSurroundings
to implement some logic checks for specific cases. For brevity sake, I have excluded all but one of the cases. It is in this function which my error occurs.
#include <vector>
bool checkSurroundings(std::vector<std::vector<int>>::iterator col_it,std::vector<int>::iterator row_it, int index_column, int index_row, int max_row_size, int max_col_size){
bool is_surrounded = false;
switch(index_column){
case 0:
col_it++;
switch(index_row){
case 0:
if(*(row_it+1)==1 && *(col_it)[index_row]==1) //error here
is_surrounded = true;
break;
//other cases follow
}
break;
//other cases follow
}
}
int closedIsland(std::vector<std::vector<int>>& grid) {
int max_column_size = grid.size();
int max_row_size = grid[0].size();
int closed_island_count = 0;
bool is_surrounded = false;
for(std::vector<std::vector<int>>::iterator column_it = grid.begin(); column_it!=grid.end(); column_it+1){
for(std::vector<int>::iterator row_it = column_it->begin(); row_it!= column_it->end(); row_it+1){
auto index_column = std::distance(column_it,grid.end());
auto index_row = std::distance(row_it,column_it->end());
if(*row_it == 0){
is_surrounded = checkSurroundings(column_it,row_it,index_column,index_row,max_row_size,max_column_size);
if(is_surrounded)
closed_island_count++;
}
}
}
return closed_island_count;
}
The code above compiles (apart from the error) using g++ -std=c++17
I am running into the following error:
error: indirection requires pointer operand ('std::vector<int, std::allocator>' invalid) if(*(row_it+1)==1 && *(col_it)[index_row]==1)
I was expecting this to work by the following logic: col_it
is a vector<vector<int>>::iterator
type so dereferncing the iterator *(col_it)
should give me the vector<vector<int>>
itself and by using []
notation I should be able to access the inner vector. Why does this not work in this case?