Range-based for loop in C++

Level 3108 keystrokes

A range-based for loop visits each string in the vector in order and prints apple, banana and cherry on separate lines.

C++ code

// A vector holding three strings
1vector<string> fruits = {"apple", "banana", "cherry"};
// f refers to each element in turn; const string& avoids a copy and forbids changes
2for (const string& f : fruits) {
// Prints the current fruit on its own line
3 cout << f << endl;
4}

Output

apple
banana
cherry
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C++ code and how often they appear.

  • "× 6
  • <× 5
  • ,× 2
  • ;× 2
  • {× 2
  • }× 2
  • :× 1
  • (× 1
  • )× 1
  • &× 1

More C++ examples at level 3

← C++ typing practice