C++map遍歷

#include <iostream>
#include <map>

using namespace std;

int main() {
    map<int, int> _map;
    _map[0] = 1;
    _map[1] = 2;
    _map[10] = 10;

    map<int, int>::iterator iter;
    iter = _map.begin();
    while(iter != _map.end()) {
        cout << iter->first << " : " << iter->second << endl;
        iter++;
    }

    // 也可以使用for循環遍歷
    /*
    for(iter = _map.begin(); iter != _map.end(); iter++) { //如果使用for循環遍歷map,不能寫成 ‘<’ 的形式
        cout << iter->first << " : " << iter->second << endl;
    }
    */
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章