DigestCPP

Lets Understand With Example

  • Home
  • Design Principal
  • Design Patterns
  • C++ 11 Features
  • C++11 Multithreading
  • Contact Us

range based for loops c++11

Range Based For Loops

It is the new form of for loop, it iterates ALL elements of given range, array or  stl collection(like vector).

Its syntax:  for(ele : coll){ statement;}  //ele is deceleration of each element and coll is collection

 
 //Array 
int arr[]{1,2,3,4,5,6,7,8,9};
//Use reference with const, if want to read only
for(const auto & ele: arr)
{
std::cout<<ele<<" ";
}
std::cout<<std::endl;
//Use reference if want to modify
for(auto & ele: arr)
{
std::cout<<ele*2<<" ";
}
std::cout<<std::endl;

Complete source code with example:

#include<iostream>
#include<vector>

int main()
{
std::cout<<"Range Based for Loops"<<std::endl;

//Array
int arr[]{1,2,3,4,5,6,7,8,9};
//Use reference with const, if want to read only
for(const auto & ele: arr)
{
std::cout<<ele<<" ";
}
std::cout<<std::endl;
//Use reference if want to modify
for(auto & ele: arr)
{
std::cout<<ele*2<<" ";
}
std::cout<<std::endl;

//Vector
std::vector<int> v{1,2,3,4,5};
//Use reference with const, if want to read only
for(const auto & ele: v)
{
std::cout<<ele<<" ";
}
std::cout<<std::endl;

//If want to use begin() and end(),they are provided by stl only
for(auto pos=v.begin(); pos!=v.end();++pos)
{
auto& ele = *pos;
std::cout<<ele<<" ";
}
std::cout<<std::endl;


return 0;
}

Output:

Range Based for Loops
1 2 3 4 5 6 7 8 9
2 4 6 8 10 12 14 16 18
1 2 3 4 5
1 2 3 4 5 

Primary Sidebar




DigestCPP © 2023. All rights reserved.

    About Privacy Policy Terms and Conditions Contact Us Disclaimer