Building a New Vector
Sometimes you want to know not only how many elements meet a condition, but also which ones. Then start with an empty vector and add each matching element to it with push_back():
std::vector<int> temperatures = {18, 24, 27, 15, 31, 22, 29};
std::vector<int> hot = {};
for (int temperature : temperatures) {
if (temperature >= 25) {
hot.push_back(temperature);
}
}
std::cout << "Hot days: " << hot.size() << std::endl;
for (int temperature : hot) {
std::cout << temperature << " ";
}
std::cout << std::endl;Hot days: 3
27 31 29 std::vector<int> hot = {}; creates a vector with no elements. You can also write just std::vector<int> hot;: unlike an int without a value, a vector without a value doesn't hold garbage, it's empty. Each push_back() adds one element at the end, so the new vector keeps the order of the original one. The original vector stays as it was, and hot.size() tells you how many elements you collected. To print the new vector, you need another loop, because std::cout << hot doesn't work.
The new vector doesn't have to hold the same values. This loop builds a vector with every number doubled:
std::vector<int> numbers = {3, 8, 5};
std::vector<int> doubled = {};
for (int number : numbers) {
doubled.push_back(number * 2);
}
for (int number : doubled) {
std::cout << number << " ";
}
std::cout << std::endl;6 16 10 Create the new vector before the loop, just like a sum or a counter. Inside the loop, every iteration would start with a new empty vector, and after the loop, the vector wouldn't exist at all.
Instructions
- 1
Create an empty vector
evenNumbersof typestd::vector<int>. Then go throughnumbersand add every even number toevenNumberswithpush_back(). A number is even whennumber % 2 == 0. - 2
After that loop, print the elements of
evenNumberson one line, after the textEven:and separated by spaces, the same way the program prints all the numbers. The output isEven: 12 30 18 4. - 3
On the next line, print how many even numbers there are, with
evenNumbers.size():Count: 4.