beginner 2d vector errors

I have a 2d vector storing a grid. I want to edit the grid based on coordinates which are stored in another vector and am running into a type grid does not provide subscript operator error. Here is how the vector is created

1
2
3
4
5
6
7
        std::vector<int> tempVector;
	for (int i=0; i<gridColumns; i++) {
		tempVector.push_back(GC_EMPTY);
	}
	for (int i=0; i<gridRows; i++) {
		grid.push_back(tempVector);
	}


then say I want to empty the grid spaces based on coordinates in another vector I am trying to do so with the code below

1
2
3
4
5
    void empty(Grid* grid, std::vector<int> pos){
	     for(int i=0;i<pos.size();i=i+2){
		    grid[pos[i]][pos[i+1]] = 0;
	    } 
    }


Thanks in advance
Your grid is a std::vector<std::vector<int>>.
If you call grid[pos[i]][pos[i+1]], your second index has nowhere to go.

Calling (grid[pos[i]])[pos[i+1]] might work though, because the extra brackets make it clear that the second index belongs to whatever was found at the position indicated by the first index and that happens to be a vector that can handle it.

As an example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <vector>

int main(int argc, char** argv)
{
    std::vector<std::vector<int>> grid;
    for (int i=0; i<4; i++)
    {
        std::vector<int> column;
        for (int j=0; j<4; j++)
        {
            column.push_back((4*i)+j);
        }
        grid.push_back(column);
    }
    for (int i=0; i<4; i++)
    {
        for (int j=0; j<4; j++)
        {
            std::cout << (grid[i])[j] << "\t";
        }
        std::cout << std::endl;
    }
    return 0;
}


Kind regards, Nico
Calling (grid[pos[i]])[pos[i+1]] might work though
I tried this and still get an error type 'Grid' does not provide a subscript operator any other ideas?

edit: pretty sure the error has to do with it being a pointer but still not having any luck fixing it
Last edited on
There is nothing in your code snippets to tell us what a Grid is, so it's impossible to say what the problem may be. Certainly, if grid in the second snippet points to a single item (such as a vector) if the first index is not 0 you will have undefined behavior, but it's impossible to say with certainty given the lack of context.
Topic archived. No new replies allowed.