1. 程式人生 > >c++你不知道的用法之foreach篇

c++你不知道的用法之foreach篇

// arraytest.cpp : 定義控制檯應用程式的入口點。
//

#include "stdafx.h"
#include <iostream>
#include<vector>
int _tmain(int argc, _TCHAR* argv[])
{
	int nums[3] = { 0, 1, 2 };
	std::vector<int>vs = { 0, 1, 2, 3, 4 };
	for (int num : nums)
	{
		std::cout << num << "\t";
	}
	std::cout << std::endl;
	for (int v : vs)
	{
		std::cout << v<<"\t";
	}
	std::cout << std::endl;
	for each (int num  in nums)
	{
		std::cout << num << "\t";
	}
	std::cout << std::endl;
	for each (int v  in vs)
	{
		std::cout << v << "\t";
	}
	system("pause");	
	return 0;
}

如果你使用過c#或者java你肯定會對其中的foreach用法十分熟悉,因為在特定的迴圈操作中它實在是太方便了。其實在c++中也提供了類似的用法,在這裡提供了兩種用法,需要注意的是下面那個是c++ foreach用法,記住for和each是分開的。