Note 10.6.1.
push_back
adds a specified element to the end of the vector, pop_back
removes element from the end of a vector.
-1
, and then display them. In such a case, we do not know the size of the vector beforehand. So we need wish add new values to the end of a vector as the user inputs them. We can use then vector function push_back
for that purpose.
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> values;
int c, i;
size_t len;
cin >> c;
while (c != -1) {
values.push_back(c);
cin >> c;
}
len = values.size();
for (i = 0; i < len; i++) {
cout << values[i] << endl;
}
}
push_back
adds a specified element to the end of the vector, pop_back
removes element from the end of a vector.
push_back
function to add even numbers less than or equal to 10 to the vector values
.nums.push_back(3)
, what will be returned by nums.size()
?
make_even
function that loops through vec
, adds 1 to any elements that are odd, and returns the new vector.
vector<int> numbers(5);
int size = 5;
for (int i = 0; i < size; i++) {
numbers[i] = i;
}
int end = 4;
for (int i = 0; i < size; i++) {
numbers[i] = numbers[end];
end--;
}
for (int i = 0; i < size; i++) {
cout << numbers[i] << " ";
}
cout << endl;
i
is 3 we copy from end = 1
copying the values we already changed.