c++ - stl标准库中map容器的使用
怪我咯
怪我咯 2017-04-17 13:59:17
0
2
309
#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函数外赋值

怪我咯
怪我咯

走同样的路,发现不同的人生

reply all(2)
洪涛

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:

int a;
a = 1;

int main() {
   ...
}

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

int a = 1;

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. . .

map<int, int> tmp;
auto shit = tmp[1] = 1;
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template