C++ map - expression must be an integral constant

2019-09-06 20:26发布

This question already has an answer here:

#include <map>
#include <string>

std::map<std::string, int> foo;
foo["bar"] = 1;

Why do I get the error "expression must be an integral constant expression" in visual studio 12?

I can't work this one out...

1条回答
疯言疯语
2楼-- · 2019-09-06 21:23

You need to place the code inside a function.

#include <map>
#include <string>

void xyz()
{
   std::map<std::string, int> foo;
   foo["bar"] = 1;
}

I verified VS 2013 has a problem otherwise, but it works when inside a function. As others have noted, most statements aren't allowed outside of a function.

查看更多
登录 后发表回答