首页 > stl标准库中map容器的使用

stl标准库中map容器的使用

#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函数外赋值


其实不仅是map,即使换成其他类型的变量,一样报错,比如改成:

int a;
a = 1;

int main() {
   ...
}

也会报同样的错误。在函数作用域之外,只能声明和定义变量,不能对变量赋值。需要注意的是,类似

int a = 1;

这样的语句,不是变量赋值,而是一个变量定义,是可以出现在函数体之外的。


全局作用域下只能声明和初始化,单独的赋值和函数调用语句都不行。。

其实你可以这样写。。。

map<int, int> tmp;
auto shit = tmp[1] = 1;
【热门文章】
【热门文章】