Vector insert in C++

Level 3109 keystrokes

insert puts a new value before the given iterator position. v.begin() + 2 is index 2, so 3 goes between 2 and 4, the later elements move back, and 1 2 3 4 5 is printed.

C++ code

// The 3 is missing
1vector<int> v = {1, 2, 4, 5};
// Inserts 3 before index 2 (the 4); the 4 and 5 shift one position back
2v.insert(v.begin() + 2, 3);
// Prints 1 2 3 4 5
3for (int n : v) {
4 cout << n << " ";
5}
// Ends the line after the loop
6cout << endl;

Output

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.

  • <× 7
  • ,× 4
  • ;× 4
  • (× 3
  • )× 3
  • .× 2
  • "× 2
  • {× 2
  • }× 2
  • :× 1

More C++ examples at level 3

← C++ typing practice