Aluepohjainen silmukalle C++:ssa

Aluepohjainen for silmukka C++:ssa on lisätty C++ 11:stä lähtien. Se suorittaa for-silmukan alueella. Käytetään luettavampana vastineena perinteiselle silmukalle, joka toimii useilla arvoilla, kuten kaikki elementit säilössä.

  for ( range_declaration : range_expression )      loop_statement    Parameters :    range_declaration :   a declaration of a named variable, whose type is the  type of the element of the sequence represented by  range_expression, or a reference to that type. Often uses the auto specifier for automatic type  deduction.   range_expression :   any expression that represents a suitable sequence  or a braced-init-list.   loop_statement :   any statement, typically a compound statement, which is the body of the loop. 

C++ toteutus:

C++
// Illustration of range-for loop // using CPP code #include  #include  #include  #include  using namespace std; // Driver int main() {  // Iterating over whole array  vector v = {0, 1, 2, 3, 4, 5};  for (auto i : v) cout < < i  < < ' ';  cout  < < '
';  // the initializer may be a braced-init-list  for (int n : { 0, 1, 2, 3, 4, 5 })  cout  < < n  < < ' ';  cout  < < '
';  // Iterating over array  int a[] = { 0, 1, 2, 3, 4, 5 };  for (int n : a)  cout  < < n  < < ' ';  cout  < < '
';  // Just running a loop for every array  // element  for (int n : a)  cout  < < 'In loop'  < < ' ';  cout  < < '
';  // Printing string characters  string str = 'Geeks';  for (char c : str)  cout  < < c  < < ' ';  cout  < < '
';  // Printing keys and values of a map  map KARTTA({ { 1, 1 }, { 2, 2 }, { 3, 3 } });  for (auto i : MAP) cout < < '{'  < < i.first  < < ', '  < < i.second  < < '}
'; } 

Lähtö
0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5 In loop In loop In loop In loop In loop In loop G e e k s {1, 1} {2, 2} {3, 3} 


C++ 17 tai uudempi: Aluepohjaisia ​​silmukoita voidaan käyttää myös seuraavien karttojen kanssa:

for (auto& [key, value]: myMap) {  cout  < < key  < < ' has value '  < < value  < < std::endl; } 

Tässä [avain, arvo] toimii kuin parin elementit johon pääsee suoraan ilman ensimmäistä tai toista avainsanaa.