vector init loop trouble

closed account (oGhfSL3A)
What I want is a 2 dimensional vector of pointers to elements in another vector.
I'm probably missing something obvious as this is such a simple piece of code, otherwise I've been using vectors wrong for ages.

I expected this to output a bunch of 87s. It actually outputs some 87s, some random numbers:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
    std::vector<int> allnum;
    std::vector<std::vector<int* >> grid;

    for(unsigned i=0; i<10; i++){
        std::vector<int* > tempVect;
        for (unsigned ii=0; ii<10; ii++){
            int num1=87;
            allnum.push_back(num1);
            tempVect.push_back(&allnum.back());
        }
        grid.push_back(tempVect);
    }

    for(unsigned i=0; i<10; i++){
        for(unsigned ii=0; ii<10; ii++){
            std::cout << *grid[i][ii] << "\n";
        }
    }


Thanks in advance! (:
Last edited on
You're using the vector wrong:

http://www.cplusplus.com/reference/vector/vector/push_back/

If a reallocation happens, all iterators, pointers and references related to the container are invalidated.
From http://www.cplusplus.com/reference/vector/vector/push_back/
If a reallocation happens, all iterators, pointers and references related to the container are invalidated.


In other words the pointers that you hold are likely to contain addresses to invalid space. That is not what you want.

Make a different kind of wrapper, if you want to hide the index math.
closed account (oGhfSL3A)
Ah! thanks.
Topic archived. No new replies allowed.