0

So for some reason this works in a class contructor but not outside a class I was wondering as to why and how could I get my map to work outside a class.

#include <iostream>
#include <string>
#include <map>


typedef std::map <std::string, int> idMap;

idMap type_id;


type_id["Moon"] = 1;
type_id["Star"] = 2;
type_id["Sun"] = 3;


int main()
{

    std::cout << type_id["Moon"] << std::endl;

}

The compiler errors I get are as follows

11:1: error: 'type_id' does not name a type 12:1: error: 'type_id' does not name a type 13:1: error: 'type_id' does not name a type 

I am looking for an example like this that would work, also if you can tell me why this won't work.

gsamaras
  • 71,951
  • 46
  • 188
  • 305
killer
  • 372
  • 1
  • 5
  • 15
  • 1
    At what point of program execution do you think `type_id["Moon"] = 1;` (and the other two) should be executed? (The language specification does not permit this outside of functions) – UnholySheep Sep 12 '17 at 07:53
  • in a larger program I am trying to create I am hoping essentially to put my map into a header so I can use it in other parts of my program – killer Sep 12 '17 at 07:58

1 Answers1

4

Your main should look like this:

int main()
{
   type_id["Moon"] = 1;
   type_id["Star"] = 2;
   type_id["Sun"] = 3;
   std::cout << type_id["Moon"] << std::endl;
}

You cannot put these statements outside of a function (in that case main()).


Or if you really want to populate your map outside main(), you could it by using a list initializer constructor, like this:

idMap type_id { {"Moon", 1}, {"Star", 2}, {"Sun", 3} };

This approach works for a header file as well, like this:

myHeader.h

#include <string>
#include <map>

typedef std::map <std::string, int> idMap;

idMap type_id { {"Moon", 1}, {"Star", 2}, {"Sun", 3} };

main.cpp

#include <iostream>
#include "myHeader.h"

int main() {
    std::cout << type_id["Moon"] << std::endl;
}
gsamaras
  • 71,951
  • 46
  • 188
  • 305
  • 1
    Alternatively OP may be looking to use the list initializer constructor of `std::map`? (e,g,: `idMap type_id { {"Moon", 1} };`) – UnholySheep Sep 12 '17 at 07:56
  • 1
    thanks for the answer I was trying to for the life of me – killer Sep 12 '17 at 08:03
  • 1
    sooo this isn't a duplicate who ever marked it as such did I know it had to be initialized I would have found that question. – killer Sep 12 '17 at 08:39