Search code examples
c++arraysvectorhashmap

Initialization of a hash_map in C++


I've created a map in C++ to store directions for different chess pieces using the following structure:

map<Piece, vector<tuple<Offset, Type, Color>>> PIECE_DIRECTIONS;

When attempting to add elements to the map, such as:

PIECE_DIRECTIONS[Pawn].push_back(tuple<Up, Push, Red>);
PIECE_DIRECTIONS[Soldier].push_back(tuple<Up, Push, Red>);

I'm getting the error message 'This declaration has no storage class or type specifier.' How can I resolve this issue? Are there alternative ways to achieve the same goal, such as using vectors or arrays instead of a map?

Is accessing elements in a map faster compared to arrays and vectors? In my specific case, the speed of accessing elements is crucial, and methods like insertions and deletions are not a significant consideration.


Solution

  • You will get something like this (I did not add the vector yet, but that adds on level of extra {} for initialization). I just wanted to give you an idea. ;)

    #include <string>
    #include <map>
    
    enum class Piece
    {
        Pawn,
        Bishop,
        Rook
    };
    
    enum class Color
    {
        Black,
        White
    };
    
    struct Direction
    {
        int horizontal;
        int vertical;
    };
    
    struct Movement
    {
        Color color;
        Direction direction;
    };
    
    int main()
    {
        std::map<Piece,Movement> moves{
            { Piece::Pawn, // <- key of your map, e.g. a Piece enum value
             { 
                Color::White,   // First member of Movement, e.g. Color enum value
                {0,1}           // Second member of Movement, Direction {0 horizontal, 1 vertical)
             }
            },
            { Piece::Bishop, { Color::Black, {8,8} } }
        };
    
        return 0;
    }