Const reference in C++

Level 4188 keystrokes

Passes a vector to a function as a const reference, which avoids copying it and forbids changing it, then prints its size and elements.

C++ code

// const vector<int>&: no copy is made, and the function cannot modify v
1void printVector(const vector<int>& v) {
// Print the number of elements: Size: 5
2 cout << "Size: " << v.size() << endl;
// Read each element (reading is allowed through a const reference)
3 for (int n : v) {
// Print the elements separated by spaces: 1 2 3 4 5
4 cout << n << " ";
5 }
6 cout << endl;
7}
8
9vector<int> nums = {1, 2, 3, 4, 5};
// nums is passed by reference without being copied
10printVector(nums);

Output

Size: 5
1 2 3 4 5 
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.

  • <× 14
  • ;× 5
  • ,× 4
  • "× 4
  • (× 4
  • )× 4
  • {× 3
  • }× 3
  • :× 2
  • >× 2

More C++ examples at level 4

← C++ typing practice