×

C++ STL Tutorial

C++ STL Algorithm

C++ STL Arrays

C++ STL String

C++ STL List

C++ STL Stack

C++ STL Set

C++ STL Queue

C++ STL Vector

C++ STL Map

C++ STL Multimap

C++ STL MISC.

Range-based loop in C++ (similar to for-each loop)

C++ Range-based loop: Here, we are going to learn about the range-based loop in C++, which is similar to the for-each loop. By Sanjeev Last updated : December 11, 2023

Range-based loop in C++ (enhanced for loop)

The for loop is used to execute a block of statements multiple times if the user knows exactly how many iterations are needed or required.

After the release of C++ 11, it supports an enhanced version of for loop, which is also called for-each loop or enhanced for loop. This loop works on iterable like string, array, sets, etc.

Syntax

Syntax of range-based (for-each/enhanced for loop):

for (data_type variable : iterable){
    //body of the loop;
}

It stores each item of the collection in variable and then executes it.

Note: auto keyword can be used instead of data_type which automatically deduce the type of the element. So type error can be reduced.

Traversing an array using range-based (for-each like) loop

C++ code to demonstrate example of range-based loop with an array.

// C++ program to demonstrate example of 
// range-based loop (for-each/ enhanced for loop)
#include <iostream>

using namespace std;

int main() {
  int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};

  cout << "\n Demonstration of for-each in C++" << endl;

  // Notice that instead of int, auto is used
  // it automatically checks for the type of
  // the variable so type error can be reduced
  // using auto keyword

  for (auto x: arr) {
    cout << " " << x << endl;
  }

  return 0;
}

Output

Demonstration of for-each in C++
 1 
 2 
 3 
 4 
 5 
 6 
 7 
 8 
 9
 

Traversing a vector using range-based (for-each like) loop

We can also use a range-based loop to traverse a vector to access and manipulate its elements.

Consider the below example: Traversing a vector using a range-based loop.

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

int main() {
  // Creating a vector of strings
  vector <string> cities {
    "Mumbai",
    "New Delhi",
    "Banglore"
  };

  // Traversing the vector using type
  cout << "Elements of vector (by specifying the type): " << endl;
  for (string city: cities) {
    cout << city << endl;
  }
  // Traversing the vector with auto keyword
  cout << "Elements of vector (with auto keyword): " << endl;

  for (auto city: cities)
    cout << city << endl;

  return 0;
}

Output

Elements of vector (by specifying the type): 
Mumbai
New Delhi
Banglore
Elements of vector (with auto keyword): 
Mumbai
New Delhi
Banglore

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.