logo CodeStepByStep logo


Language/Type: C++ Vector collections
Related Links:
Author: Marty Stepp (on 2016/06/16)

Write a function named removeBadPairs that accepts as a parameter a reference to a Vector of integers, and removes any adjacent pair of integers in the list if the left element of the pair is larger than the right element of the pair. Every pair's left element is an even-numbered index in the list, and every pair's right element is an odd index in the list. For example, suppose a variable named vec stores the following element values:

{3, 7, 9, 2, 5, 5, 8, 5, 6, 3, 4, 7, 3, 1}

We can think of this list as a sequence of pairs:

{3, 7, 9, 2, 5, 5, 8, 5, 6, 3, 4, 7, 3, 1}

The pairs 9-2, 8-5, 6-3, and 3-1 are "bad" because the left element is larger than the right one, so these pairs should be removed. So the call of removeBadPairs(vec); would change the vector to store:

{3, 7, 5, 5, 4, 7}

If the vector has an odd length, the last element is not part of a pair and is also considered "bad;" it should therefore be removed by your function.

If an empty vector is passed in, the vector should still be empty at the end of the call.

Constraints: Do not use any other arrays, vectors, or other data structures to help solve this problem, though you can create as many simple variables as you like.

Type your solution here:

This is a function problem. Write a C++ function as described. Do not write a complete program; just the function(s) above.

You must log in before you can solve this problem.

Log In

If you do not understand how to solve a problem or why your solution doesn't work, please contact your TA or instructor.
If something seems wrong with the site (errors, slow performance, incorrect problems/tests, etc.), please

Is there a problem? Contact a site administrator.

© Marty Stepp, all rights reserved.