← Back to STL Containers
Question 564
Print Every Other Element
Print Every Other Element
Write a functionvoid printEveryOther(const vector<int>& v)that prints the elements at positions 0, 2, 4, ... each followed by a single space, and then a newline. Walk the vector with one iterator and move it withadvance(it, 2). Before each jump, make sure at least 2 steps remain (usedistance(it, v.end())); if fewer remain, leave the loop. The newline is printed exactly once, after the loop, no matter how it ended. For an empty vector print just the newline. For {1, 2, 3, 4, 5} the function prints the line1 3 5; for {1, 2, 3, 4} it prints1 3. The hidden test only calls your function — it prints nothing else. Do NOT write a main function.
Expected Output:
1 3 5 1 3
= newline. The output ends with a newline — print one after the last line.
Hints4 available
Sign in to use hintsTopics:
STL ContainersIterators
1
Tab to indent (Esc then Tab to move on) · Ctrl+Enter to run · Shift+Alt+F to format · Ctrl+Space to expand shortcuts (cout, fori)
Your Output
Run your code to see the output here...
Test Cases
Run your code to see test case results.