Range Based For


Range Based For is new in c++11

void RangeBasedFor()
{
	nullptr_t pN = nullptr;
	void *pV = reinterpret_cast(1);
	int *pI = reinterpret_cast(2);
	void *arr[] = { pV, pN, pI };
	std::cout << "enumerating void *arr[] with Range Based For syntax" << std::endl;
	//other options: auto i, auto&& i
	for (const auto &i : arr) //auto or int, arr can be replaced directly by {2, 3}
		std::cout << i << std::endl;

	std::vector arr2 = { 3, 4 };
	std::cout << "enumerating vector with Range Based For syntax" << std::endl;
	for (const auto &i : arr2) //works for both int[] and vector
		std::cout << i << std::endl;
	std::cout << "enumerating vector with regular for loop" << std::endl;
	for(std::vector::iterator i = arr2.begin(); i != arr2.end(); ++i) //only for vector
		std::cout << *i << std::endl;
}

 

Output:
enumerating void *arr[] with Range Based For syntax
0000000000000001
0000000000000000
0000000000000002
enumerating vector with Range Based For syntax
3
4
enumerating vector with regular for loop
3
4

 

Next Post
Comments are closed.
%d bloggers like this: