LearnFrenzy
Sign in Take a free test

Arrays and Vectors · Find the Error · Question 7

Error: push_back on a const vector Answer, explanation & discussion

  • Find the error
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

The program below does not compile. Which statement correctly describes the problem?

main.cpp
#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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links