【C++】04 循环的高级用法


link

1.C++中的Range-based的循环

for ( range_declaration : range_expression ) 
    loop_statement

​ 如上面代码所示,这个for中有两个参数,一个是参数声明,另一个是循环的主体。可以注意的是,它甚至没有大括号。
​ 以下是一些实例:

#include <iostream>
#include <vector>
#include <map>
using namespace std;

int main(){
	//使用vector循环
	vector<int> v = {0, 1, 2, 3, 4, 5};
	for (auto i : v)
			cout << i << ' ';
		
	//使用数组循环
	int a[] = {0, 1, 2, 3, 4, 5};
	for(int n : a)
		cout << n << ' ';	
		
	//使用没声明的数组循环
	for(int n : {0, 1, 2, 3, 4, 5})
		cout << n << ' ';
	
	//使用字符串循环
	string str="Geeks";
	for(char c : str)
		cout << n << ' ';
		
	//使用MAP类型类循环
	map <int, int> MAP({{1, 1}, {2, 2}, {3, 3}});
    for (auto i : MAP)
        std::cout << '{' << i.first << ", " 
                  << i.second << "}\n";
}

2.C++中的for_each循环

for_each (InputIterator start_iter, InputIterator last_iter, Function fnc)

​ 从模板中看出,第一个参数是 起始位置,第二个是 最后位置, 第三个是 执行的函数。有以下例子:

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

void printx2(int a){
	cout << a * 2 << " ";
}
struct Class2{
	void operator() (int a){
		cout << a * 3 << " ";
	}
} ob1;


int main(){
	int arr[5] = { 1, 5, 2, 4, 3 };
	cout << "Using Arrays:" << endl;
	//这是输出初始的数组
	
	for_each(arr, arr + 5, printx2);
	//执行的主体已经在for_each的循环中了。
	//可见,我们会让它执行5次。
	
	for_each(arr, arr + 5, ob1);
	//直接调用对象,对数组中的5个元素进行执行
	
	vector<int> arr1 = { 4, 5, 8, 3, 1 };
	//执行数组的向量

	for_each(arr1.begin(), arr1.end(), printx2);
	//从vector中取数循环

	for_each(arr1.begin(), arr1.end(), ob1);
	//使用对象的方法,循环
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值