c++dictionaryc++17member-access

Accessing elements of std::vector<std::map<int, unsigned char>>grid gives error "Expression must have a class type"


I've searched far and wide and can't find an answer. Why can't I access the elements? It gives me the error: "Expression must have a class type". I have no idea what this means. Can someone give me a solution to this please?

#include <iostream>
#include <vector>
#include <map>
#include <utility>
#include <algorithm>
int main()
{
    std::vector<std::map<int, unsigned char>>grid =
    {
        {std::make_pair(1,'-'), std::make_pair(2,'-'), std::make_pair(3,'-') },
        {std::make_pair(4,'-'), std::make_pair(5,'-'), std::make_pair(6,'-') },
        {std::make_pair(7,'-'), std::make_pair(8,'-'), std::make_pair(9,'-') }
    };
//This doesn't work
    std::cout << grid.at(0).at(0).second
    
}

Solution

  • It seems you mean

     std::cout << grid.at(0).at(1);
    

    instead of

    std::cout << grid.at(0).at(0).second;
    

    It is the same as

    std::cout << grid.at( 0 ).begin()->second;
    

    provided that the element with the key 1 is the first element in the selected map.

    That is in the second call of the member function at you have to specify a key in the map. In this case the function will return the corresponding value that in your case has the scalar type unsigned char.

    The member function at is declared like

    T& at(const key_type& x);
    const T& at(const key_type& x) const;
    

    For a given key it returns the corresponding value.

    Within the map at index 0 in the vector initialized like

    {std::make_pair(1,'-'), std::make_pair(2,'-'), std::make_pair(3,'-')
    

    keys are 1, 2, and 3.

    So you may use expressions

    grid.at(0).at(1)
    grid.at(0).at(2)
    grid.at(0).at(3)