-2

Been trying to find out why I can't seem to get 2d vectors to work properly. Tried this and it only works if I initiliaze the vector of vectors as a local variable. Otherwise I get an out of range error.

vector <string> allSymbols;

std::vector<std::vector<bool>> wholeMap(allSymbols.size(), std::vector<bool>(allTerms.size() + 2));

void fillWholeMap()
{


    cout << allSymbols.size() << endl;
    cout << allTerms.size() << endl;
    for (int i = 0; i < allSymbols.size(); i++)
    {
        for (int j = 0; j < allTerms.size() + 2; j++)
        {
            wholeMap[i][j]=false;
        }
    }
}
robo
  • 7
  • 5
  • I have no idea what you expect your second line of code to accomplish. Maybe you can describe your higher-level goal. Do you want a 2D-matrix of boolean flags? Maybe use an existing matrix class or roll your own simple one with a clean interface. – 5gon12eder Feb 21 '15 at 02:38
  • Please a whole [mcve](http://stackoverflow.com/help/mcve). Make sure you do initialise `wholeMap` **after** you have filled `allSymbols` and `allTerms`. Alternative is to initialise `wholeMap` with a 0 size and to use `vector::push_back()` method to dynamically add. – tofi9 Feb 21 '15 at 02:39
  • Sorry, Yes I am trying to create a 2d vector that is all boolean flags. I am having trouble initializing the 2d vector. I do initialize the other two first and I have tried vector::push_back() My second line of code is my attempt to create a vector of vector with bools inside. This vector of vectors is supposed to have the size I defined. However, I am finding it is not reserving any space. – robo Feb 21 '15 at 02:52
  • The power of C++ is utilized best if you use appropriate data structures that encapsulate the complicated stuff so you can solve one small problem at a time. You can get some inspirations for writing a simple matrix class from [this answer](http://stackoverflow.com/a/2076668/1392132). Otherwise, you could use an external library. In addition, I recommend you stay away from `std::vector` and use `std::vector` instead unless you know exactly what you are doing. It will save you a lot of bad surprises; `std::vector` is the enfant terrible of the STL. – 5gon12eder Feb 21 '15 at 03:23

1 Answers1

0

A global variable is initialised even before main() is called. Your wholeMap is being initialised with size 0 when you create it as a global variable. This is because the size of allSymbols is 0 at that time.

tourniquet_grab
  • 792
  • 9
  • 14