map

Write your question here.

Cant solve this problem:

string s:

s=cellToSymbol[Cell::closed];

gives:

error C2678: binary '[': no operator found which takes a left-hand operand of type 'const std::map<Cell,std::string,std::less<_Kty>,std::allocator<std::pair<const _Kty,_Ty>>>



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
 const map<Cell, string> cellToSymbol{ {Cell::closed, ""},
					 {Cell::open, ""},
					 {Cell::flagged, "@<"} };

void Tile::open()
{
	if (state == Cell::flagged) {
		return;
	}
	state = Cell::open;

	isMine = true;

	if ( isMine == true) {
		set_label("X");
		set_label_color(Color::red);
	}
}

void Tile::flag()
{
        string s;
	if (state == Cell::flagged) {
		state = Cell::closed;

                s = cellToSymbol[ Cell::closed];   //failing!!!!!
		set_label(s);

	}
	
}
My understanding is that the [] operator is not const, so it can't be used if you have a const map object.

I believe you have to either use at, which can throw exceptions, or use find.
http://www.cplusplus.com/reference/map/map/at/
http://www.cplusplus.com/reference/map/map/find/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// Example program
#include <iostream>
#include <string>
#include <map>

using std::map;
using std::string;

enum class Cell {
    closed,
    open,
    flagged  
};



const map<Cell, string> cellToSymbol = {
    {Cell::closed, ""},
    {Cell::open, ""},
    {Cell::flagged, "@<"}
};

void lag()
{
    string s = cellToSymbol.find(Cell::closed)->second;

    // If you can't be logically sure that the key is in the map,
    // check to make sure the result does not equal map.end()
    auto it = cellToSymbol.find(Cell::flagged);
    if (it != cellToSymbol.end())
    {
        std::cout << "found\n";
    }
    else
    {
        std::cout << "not found\n";
    }
}

int main()
{
    lag();
}

Last edited on
thanks :) it worked
There be raisins.

From one of the suggested reads you get from Google:
The words bugs (C++) — Vanand Gasparyan — Median 
https://medium.com/@vgasparyan1995/the-worst-bugs-c-807e0be5dbe7
closed account (E0p9LyTq)
The first documented computer bug was a real bug. A moth. Found by Grace Hopper.

http://www.anomalies-unlimited.com/Science/Grace%20Hooper.html
Topic archived. No new replies allowed.