简体   繁体   中英

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
    
}

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)

grid.at(0) will give you a std::map<int, unsigned char> . From cppreference , calling .at(key) on a map will give you the value corresponding to that key.

So if you'd done:

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

You'd see '-' from the pair (1, '-') in the first map.

If instead you wanted to get the first pair, you should use .begin() :

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

See it in action: https://ideone.com/YmLIvK

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM