簡略記錄使用 C++11 特性對 vector 和 map 容器進行遍歷,用到了多個方法,對於方法的取捨見仁見智
包括但不限於以下方法:
- 普通迭代器方法
- auto關鍵字識別迭代器方法
- auto關鍵字範圍遍歷方法
- for_each加函數遍歷方法
- for_each與lamanda表達式組合方法
/*================================================================
* Copyright (C) 2017 Renleilei. All rights reserved.
*
* 文件名稱:013_iterator.cpp
* 創 建 者:Renleilei ([email protected])
* 創建日期:2017年11月05日
* 描 述:熟悉iterator用法與實現c++11的新特性及lambda表達式[lamanda is wrong! lambda is right!]
* 版 本: Version 1.00
* 編譯方法: g++ -std=c++11 -o main 013_iterator.cpp -O3 -g -Wall
================================================================*/
#include <vector>
#include <map>
#include <iostream>
#include <algorithm>
#include <functional>
#include <string>
using namespace std;
void printElem(int& elem);
void printElem_1(int elem, const char* prefix);
int main()
{
/* vector的第一種初始化方法 */
int ia[] = {1, 2, 3};
cout<<"sizeof(ia)/sizeof(int) = ["<<sizeof(ia)/sizeof(int)<<"]"<<endl;
vector<int> ivec(ia, ia + sizeof(ia)/sizeof(int));
/* vector的第二種初始化方法 */
vector<int> _vec02 = {10, 11, 12, 13, 14, 15, 16};
/* map容器的初始化方法 */
map<int, string> imapStudent;
// ====================================================================
/* vector 遍歷*/
/* 1.使用迭代器遍歷容器 */
for(vector<int>::const_iterator iter = ivec.begin(); iter != ivec.end(); ++iter){
cout<< *iter << endl;
}
/* 2.使用for_each遍歷容器 */
for_each(ivec.begin(), ivec.end(), printElem);
for_each(ivec.begin(), ivec.end(), bind2nd(ptr_fun(printElem_1), "Element: "));
/* 3.for_each 與 lambda 表達式的結合遍歷容器使代碼簡潔 */
for_each(ivec.begin(), ivec.end(), [ &](int _A){ _A = _A + 1; cout<<_A<<","<<endl;}); //output: 2, 3, 4
/* 4.for loop auto 區間遍歷 */
for(auto iter = _vec02.begin(); iter != _vec02.end(); iter++){ //基礎型迭代器與auto遍歷
cout<< (*iter) <<" ";
}
cout<<endl;
for(auto val : _vec02){ //區間遍歷
cout<< val <<" ";
}
cout<<endl;
// ====================================================================
/* map 遍歷 */
imapStudent.insert(pair<int, string>(1, "student 1")); //插入方式 - 1
imapStudent.insert(map<int, string>::value_type (2, "student 2")); //插入方式 - 2 [與方式1其實類似]
imapStudent[3] = "student 3"; //插入方式 - 3 [數組方式插入]
cout<<"map.size: "<<imapStudent.size()<<endl; //獲取map容器已存入的數據數量
/* 1.迭代器for loop普通遍歷 */
map<int, string>::iterator iter_map; //設置前向迭代器
for(iter_map = imapStudent.begin(); iter_map != imapStudent.end(); ++iter_map){ //應用前向迭代器
cout<<iter_map->first<<"-"<<iter_map->second<<" ";
}
cout<<endl;
map<int, string>::reverse_iterator iter_map2; //設置反向迭代器
for(iter_map2 = imapStudent.rbegin(); iter_map2 != imapStudent.rend(); ++iter_map2){ //應用反向迭代器
cout<<iter_map2->first<<"-"<<iter_map2->second<<" ";
}
cout<<endl;
/* 2.數組形式遍歷 */
for(int i = 1; i <= (int )imapStudent.size(); ++i){
cout<<imapStudent[i]<<" ";
}
cout<<endl;
/* 3.for loop auto 區間遍歷 */
for(auto &val_map : imapStudent){
cout<<val_map.first<<"-"<<val_map.second<<" ";
}
cout<<endl;
}
void printElem(int& elem){
cout<< elem <<endl;
}