logo CodeStepByStep logo

indexOfAll

Language/Type: C++ vector collections STL
Related Links:

Write a function named indexOfAll that accepts two references to vectors of integers a1 and a2 as parameters and that returns a new vector of integers representing all starting indexes where a2's sequence of elements appear in a1. The sequence of elements in a2 may appear anywhere in a1 but must appear consecutively and in the same order. For example, if variables called a1 and a2 store the following values:

//   index
//   0  1  2  3  4  5  6  7  8  9 10 11
a1: {1, 6, 1, 2, 1, 4, 1, 2, 1, 2, 1, 8}
a2: {1, 2, 1}

Then the call of indexOfAll(a1, a2) should return the vector {2, 6, 8} because a2's sequence of values {1, 2, 1} is contained in a1 starting at those indexes. Any two vectors with identical elements are considered to contain each other, so a call such as indexOfAll(a1, a1) should return {0}. If a1 does not contain a2, return an empty vector.

You may assume that both vectors passed to your function will have lengths of at least 1. You may not use any strings to help you solve this problem, nor functions that produce strings such as converting a vector to a string.

Function: Write a C++ function as described, not a complete program.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.