Question 7
Back to Exercise
The program below does not compile. Which statement correctly describes the problem?
#include <iostream>
#include <vector>
void add_item(const std::vector<int>& items, int x) {
items.push_back(x);
}
int main() {
std::vector<int> v;
add_item(v, 5);
std::cout << v.size() << '\n';
return 0;
}
- A x must be a reference
- B items is a reference to const, so the non-const member push_back cannot be called; take std::vector<int>& to modify it Correct
- C push_back needs two arguments
- D Vectors cannot be passed to functions
Correct Answer: Option B
const& is for functions that only read. A function that adds elements must take a non-const reference.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!