C++11:实用特性

今天逛cplusplus.com发现C++还真多了不少方便使用的特性,先了解些最常用的

初始化列表

    vector<int> tmp({1,2,3,4});
    
    vector<pair<int, int> > tmp_pair(
        {
            {1, 2},
            {3, 4}
        }
    );

或者直接初始化,跟一般的数组初始化非常像了

    vector<int> tmp = {1, 2, 3, 4};
    
    vector<pair<int, int> > tmp_pair ={
        {1, 2},
        {3, 4}
    };

for迭代

    for (int e : tmp) {
        cout<<e<<endl;
    }
    
    for(pair<int, int>& e : tmp_pair) {
        cout<<e.first<<","<<e.second<<endl;
    }

这样跟Java一样,比写显式的迭代器方便许多,尤其是C++里的迭代器声明太麻烦(好像现在可以使用auto自动判断类型了)

原文地址:https://www.cnblogs.com/lailailai/p/4323060.html