C++ for循环

本文介绍了C++中遍历容器的多种方法,包括使用传统迭代器、C++11的范围for循环以及std::for_each函数。通过实例展示了如何遍历std::vector容器,并解释了迭代器和引用在循环中的作用。

C++使用如下方法遍历一个容器:

#include "stdafx.h"

#include<iostream>

#include<vector>

int main()

{

std::vector<int> arr;

arr.push_back(1);

arr.push_back(2);

for (auto it = arr.begin(); it != arr.end(); it++)

{

std::cout << *it << std::endl;

}

return 0;

}

------------------------------------

其中auto用到了C++11的类型推导。同时我们也可以使用std::for_each完成同样的功能:

#include "stdafx.h"

#include<algorithm>

#include<iostream>

#include<vector>

void func(int n)

{

std::cout << n << std::endl;

}

int main()

{

std::vector<int> arr;

arr.push_back(1);

arr.push_back(2);

std::for_each(arr.begin(), arr.end(), func);

return 0;

}

------------------------------------

现在C++11的for循环有了一种新的用法:

#include "stdafx.h"

#include<iostream>

#include<vector>

int main()

{

std::vector<int> arr;

arr.push_back(1);

arr.push_back(2);

for (auto n : arr)

{

std::cout << n << std::endl;

}

return 0;

}

上述方式是只读,如果需要修改arr里边的值,可以使用for(auto& n:arr),for循环的这种使用方式的内在实现实际上还是借助迭代器的,所以如果在循环的过程中对arr进行了增加和删除操作,那么程序将对出现意想不到的错误。

  其实这种用法在其他高级语言里早有实现,如php,Java,甚至是对C++进行封装的Qt,foreach也是有的。 

------------------------------------

简化数组遍历语法(从vs2008开始支持) for each(auto item in vecNum) { strText.Format("%d", item); AfxMessageBox(strText); }

------------------------------------

STL函数 std::for_each(vecNum.begin(), vecNum.end(), [](int item) { CString strText; strText.Format("%d", item); AfxMessageBox(strText); } );

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值