Range based for loop is one of basic feature of c++11/c++14 standard. We will discuss some limitation of range based for loop in c++11/c++14. Let us write a simple code which will insert 20 integers into a stl vector and print the elements of vector using range based for loop.

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

vector<int> data;

int main() {

	data.reserve(20);

	// insert 20 integers in data
	for (int i=0; i < 20; i++)
		data.push_back(i);

	// print elements from vector data
	for(auto a:data)
		cout << a;
        cout << endl;
	return 0;
}

Compile and Run

bosch@bosch-Inspiron-N5050:~$ g++ -std=c++11 sample.cpp
bosch@bosch-Inspiron-N5050:~$ ./a.out 
012345678910111213141516171819

Limitation of range based for loop in c++11/c++14

In our program we used following code for printing elements of vector.

// print elements from vector data
	for(auto a:data)
		cout << a;
  • Let us suppose we need to print not all elements of vector data. we need to print only 5 of 20 elements. so it is not possible for us to print only 5 of 20 elements using range based for loop.


Related Contents to follow