putting stuff in map in global scope

Feb 5, 2016 at 10:16am
Hi, I cant really understand what this error message means when I'm doing this :
1
2
3
4
5
6
7
8
9
10
#include <map>
#include <string>

std::map<std::string, int> mp;
mp["triangle"] = 2;

int main()
{

}

'mp' does not name a type


This on the other hand works just fine like I expected the first variant would work as well!
1
2
3
4
5
6
7
8
#include <map>
#include <string>

int main()
{
std::map<std::string, int> mp;
mp["triangle"] = 2;
}

I originally did this with function pointers and I was trying to figure out whats wrong with them and why my map just wont accept them for like 2 hours :D until I saw this interesting thing. Whats really the difference between these 2?
Last edited on Feb 5, 2016 at 10:20am
Feb 5, 2016 at 10:20am
The problem is pretty obvious. There is only 1 difference between the first and the second code, and that is that one is inside main, and the other is not.

mp["triangle"] = 2;
You can't do this in the global scope. You can create the map, std::map<std::string, int> mp;, you can initialize it, but not give it values like this.

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>

using namespace std;

int x; // okay
int y = 5; // okay
x = 5; // doesnt work

int main()
{
    x = 5; // works
}


Edit: I dont have any input as to why this doesnt work, someone else will have to comment on that.
Last edited on Feb 5, 2016 at 10:27am
Feb 5, 2016 at 10:28am
Thank you very much man!
Topic archived. No new replies allowed.