Search code examples
c++multidimensional-arrayenumsstdvector

how to save vector of vector of type enum in


I have a vector of a vector where it represents my map after loading from a file, there is a problem, how can I save into it? Like at coordinate x and y is this type ?

//Field.cpp
enum Fieldtype <River,Building,Earth,Sky...>

//Logic.cpp
std::vector<std::vector<Field::Fieldtype>> my_map;
char array[10][10];

After loading my map from a txt file into a char array, now is the problem how can I save it into map?

for examle this map:

SSSSS
SSSSS
BBBBB
EEEEE

where S is my sky, B is building... I tried with

for(int x = 0; x < 6; x++)
{
   for(int y= 0; y< 6; y++)
   {
      if(array[x][y] == 'S')
         my_map.at(x).at(y) = Field::Sky;
   }

}

this gets me a vector out of range. Can somone help me?


Solution

  • What's the problem ?

    The problem is that when you have created the vector with:

    std::vector<std::vector<Field::Fieldtype>> my_map;
    

    this vector is completely empty when you try to load it. So any attempt to access to an element, even my_map[0][0], will be out of range !

    How to solve it ?

    You should populate the vector using either resize() or push_back() or a combination of both, for example:

    my_map.resize(6);     // takes care of all the x at once 
    for(int x = 0; x < 6; x++)
    {
       for(int y= 0; y< 6; y++)
       {
          if(array[x][y] == 'S')
             my_map[x].push_back(Field::Sky);   // add the y one by one 
          ...
       }
    }
    

    Further improvements

    To avoid a lot of if clauses to process the different letters, you could also create a map:

    map<char, Field::Fieldtype> mapfield; 
    

    You would populate your map with:

    mapfield['S'] = Field::Fieldtype::Sky;
    ...
    

    Then you could rewrite your loop:

    my_map.resize(5);     // takes care of all the x at once 
    for(int x = 0; x < 6; x++)
       for(int y= 0; y< 6; y++)
          my_map[x].push_back(mapfield[array[x][y]]);  
    

    A simpler but more dirty alternative would be to define :

    enum Fieldtype:char {River='R',Building='B',Earth='E',Sky='S', ...};
    

    and in the loop populate the fields with:

    my_map[x].push_back(static_cast<Fieldtype>(array[x][y]));