#include <map>
#include <iostream>
using namespace std;
map<int, int> tmp;
tmp[1] = 1;
int main()
{
map<int, int> res;
res[1] = 2;
res[3] = 2;
for (auto it : res)
{
cout << it.first << endl;
}
}
为什么map类型的变量不能在main函数外赋值
In fact, not only map, even if it is replaced with other types of variables, the same error will be reported, for example, if changed to:
will also report the same error. Outside the function scope, variables can only be declared and defined, but variables cannot be assigned values. It should be noted that something like
Such a statement is not a variable assignment, but a variable definition, and can appear outside the function body.
Only declaration and initialization can be done in the global scope, not individual assignment or function call statements. .
Actually, you can write it like this. . .