0

I want to initialize a std::map in my_cpp.h header file:

std::map<std::string, double> my_map;
my_map["name1"] = 0;
my_map["name2"] = 0;

But there was a compile error showed up:

error: ‘my_map’ does not name a type

Can someone explain why this not work for a C++ newbie? Thanks

3
  • std::map<std::string, double> my_map{{"name1", 0}, {"name2", 0}}; Commented Oct 12, 2021 at 3:08
  • 1
    Answering your question: your code doesn't work because statements must be within a body of some function. Only declarations can be present outside any function. Commented Oct 12, 2021 at 3:10
  • Thanks all the help above and the below, seems this is a very beginner and stupid question... Commented Oct 12, 2021 at 6:45

2 Answers 2

2

You can't initialize a map in a .h file like that. Those assignment statements need to be inside a function/method instead.

Otherwise, initialize the map directly in its declaration, eg

std::map<std::string, double> my_map = {
    {"name1", 0.0},
    {"name2", 0.0}
};
Sign up to request clarification or add additional context in comments.

Comments

1

The header file is just a declaration, or initialize the map directly . You can modify your code like this:

#include <map>
#include <string>

const std::map<std::string, double> my_map = {
  { "name1", 0 },
  { "name2", 0 }
};

1 Comment

The other answered first so I have him the as the resolution. But still appreciate for the help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.