Start learning free

LESSON 112 OF 667 · ARRAYS I

Slicing a Vector in C++

Lesson

TL ; DR:

Build a new vector from two positions, as in vector<string> part(v.begin() + i, v.begin() + j);. It holds the items from index i up to, not including, j. The original doesn't change.


vector<string> letters = {"a", "b", "c", "d", "e"};

vector<string> middle(letters.begin() + 1, letters.begin() + 4);
// middle is {"b", "c", "d"}

// letters is still {"a", "b", "c", "d", "e"}


Full lesson:

Sometimes you need only part of a vector, like the first few items. You can build a new vector from that part.

As with insert and erase, v.begin() + i is the position of index i. A new vector built from two positions copies the items between them.

The item at the second position is not included. So from letters.begin() + 1 to letters.begin() + 4, you get the items at 1, 2 and 3.

To go to the very end, use v.end() as the second position. It is just past the last item:

vector<string> tail(letters.begin() + 3, letters.end());
// tail is {"d", "e"}

The same works as an expression, like vector<string>(v.begin(), v.begin() + 2). That is handy in a return.

The new vector is a copy. The original stays as it was.

C++ doesn't check the positions for you. A position past the end can crash the program.


Your task

runners holds a race's runners, in the order they finished.

Put the first three in a new vector named podium. Put everyone else, from index 3 to the end, in one named rest.

The code below prints both, then the length of runners.

Expected output:

Ana Ben Cleo
Dan Eve
5
STEP 1 OF 2
    Ctrl + Enter to check