C++遍历(traversal)总结

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

  • 传统C for写法
  • 迭代器for写法
  • STL for_each写法
  • C++11迭代器autofor写法
  • C++11 for loop scope写法
  • C++11 STL for_each与lamdba表达式

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

字符串遍历

string str("abcdefg");

1.传统C for写法 

for(size_t i=0;i<str.size();i++){
    cout << str[i] << endl;
}

2.迭代器for写法

for(string::iterator it = str.begin();it != str.end();it++){
    cout << *it << endl;
}

 3.STL for_each写法

void print(char c){
    cout << c << endl;
}
for_each(str.begin(),str.end(),print);

4.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;
}

5. C++ 11 for loop scope写法

for(char c : str){
    cout << c << endl;
}

或者

for(auto c : str){
    cout << c << endl;
}

 6.C++ 11 STL for_each与lamdba表达式

for_each(begin(str),end(str),[](char c){cout << c << endl;});

向量遍历

vector<int> 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<vec.size();i++){
    cout << vec[i] << endl;
}

2.迭代器写法

for(vector<int>::iterator it = vec.begin();it != vec.end();it++){
    cout << *it << endl;
}

3.STL for_each写法

void print(int n){
    cout << n << endl;
}
for_each(vec.begin(),vec.end(),print);

4.C++11迭代器写法

for(vector<int>::iterator it = begin(vec);it != end(vec);it++){
    cout << *it << endl;
}

或者

for(auto it = begin(vec);it != end(vec);it++){
    cout << *it << endl;
}

5.C++ 11 for新语法写法

for(int n : vec){
    cout << n << endl;
}

或者

for(auto n : vec){
    cout << n << endl;
}

6.C++ 11 STL for_each与lamdba表达式

for_each(begin(vec),end(vec),[](int n){cout << n << endl;});

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值