← C++ from Scratch
Lesson 53 of 62 · 10 XP
vector
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
#include <vector>
std::vector<int> v; // empty
std::vector<int> w(5, 0); // 5 zeros
v.push_back(10); // add to the end
v.size(); // how many items
v[0]; v.back(); // the first and the last
v.pop_back(); // remove the last
v.insert(v.begin() + 1, 7); // insert at position 1
v.erase(v.begin()); // remove the first
for (int x : v) { … } // go through the items
Under the hood it's an array on the heap. When it runs out of room, a vector allocates a piece twice as big and moves
the items over; that's why push_back is O(1) on average. If the size is known in advance, v.reserve(n) removes the extra moves.
Task. Read numbers until the end of the input into a std::vector. Print: the count, then all the numbers except the even ones
(remove the even ones from the vector with erase), then the sum of the remaining ones.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.