ForEach in C++ and its Use

Last Updated On Friday 21st Jan 2022

Range Based For Loop in C++

C++ foreach

  • We need to put what data type is
  • Create a temporary variable to store each element
  • array name, data name
  • Syntax is much nicer
  • In Other Programming languages, It Something ForEach Loop

for(int n:data){} like that

foreach c++

	#include <iostream>
#include <array>

int main() {
  int data[] = {
    10,
    11,
    12,
    13,
    14,
    15,
    16
  };
  for (int n: data) {
    std::cout << n << "t";
  }
  std::cout << "n";
}
	

It returns

	10   11   12   13   14   15   16
	

You Can do it with Vector as well.

	#include <iostream>
#include <vector>
#include <array>

int main() {
  std::vector <int> data = {
    10,
    11,
    12,
    13,
    14,
    15,
    16
  };
  for (int n: data) {
    std::cout << n << "t";
  }
  std::cout << "n";
}
	

It returns the Same as well.

	10   11   12   13   14   15   16
	

Its Eliminates errors, much easier to read. It’s Much Handier When we need to iterate through every element in an array. It is a Pretty Simple Concept