C++进阶:遍历(traversal)总结

遍历简介

遍历:集合中每个元素一次且仅做一次访问。
C++中存在很多遍历方式,常见如下几种:

  1. 传统C for写法
  2. 迭代器for写法
  3. STL for_each写法
  4. C++11迭代器autofor写法
  5. C++11 for loop scope写法
  6. C++11 STL for_each与lamdba表达式

下面实例说明字符串与向量的遍历。

字符串遍历

string str("abcdefg");
  1. 传统C for写法
for(size_t i=0;i
  1. 迭代器for写法
for(string::iterator it = str.begin();it != str.end();it++){
    cout << *it << endl;
}
  1. STL for_each写法
void print(char c){
    cout << c << endl;
}
for_each(str.begin(),str.end(),print);
  1. C++11迭代器写法
for(string::iterator it = begin(str);it != end(str);it++){
    cout << *it << endl;
}

或者

for(auto it = begin(str);it != end(str);it++){
    cout << *it << endl;
}
  1. C++11 for loop scope写法
for(char c : str){
    cout << c << endl;
}

或者

for(auto c : str){
    cout << c << endl;
}
  1. C++11 STL for_each与lamdba表达式
for_each(begin(str),end(str),[](char c){cout << c << endl;});

向量遍历

vector vec;
vec.push_back(1);
vec.push_back(2);
vec.push_back(3);
vec.push_back(4);
vec.push_back(5);
  1. C写法
for(size_t i=0;i
  1. 迭代器写法
for(vector::iterator it = vec.begin();it != vec.end();it++){
    cout << *it << endl;
}
  1. STL for_each写法
void print(int n){
    cout << n << endl;
}
for_each(vec.begin(),vec.end(),print);
  1. C++11迭代器写法
for(vector::iterator it = begin(vec);it != end(vec);it++){
    cout << *it << endl;
}

或者

for(auto it = begin(vec);it != end(vec);it++){
    cout << *it << endl;
}
  1. C++11 for新语法写法
for(int n : vec){
    cout << n << endl;
}

或者

for(auto n : vec){
    cout << n << endl;
}
  1. C++11 STL for_each与lamdba表达式
for_each(begin(vec),end(vec),[](int n){cout << n << endl;});

你可能感兴趣的:(C++进阶:遍历(traversal)总结)