10.5. Vector functions¶
The best feature of a vector is its ability to resize.
A vector, once declared, can be resized from anywhere within the program.
Suppose we have a situation where we input numbers from the user and
store them in a vector till the input is -1, and then display them.
In such a case, we do not know the size of the vector beforehand.
So we need a way 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.
Note
push_back adds a specified element to the end of the vector, pop_back
removes element from the end of a vector.
#include <iostream>
#include <vector>
int main() {
std::vector<int> values;
int c;
cin >> c;
while (c != -1) {
values.push_back(c);
cin >> c;
}
std::size_t len = values.size();
for (std::size_t i = 0; i < len; i++) {
cout << values[i] << '\n';
}
}
The active code below uses the push_back function to add
even numbers less than or equal to 10 to the vector values.
1#include <iostream>
2#include <vector>
3
4void print_vec(std::vector<int> nums);
5
6int main() {
7 std::vector<int> values;
8 int i = 0;
9
10 while (i <= 10) {
11 values.push_back(i);
12 i += 2;
13 }
14 print_vec(values);
15}
Q1
Let nums be the vector { 0, 1, 2, 3, 4 }. If we run the command nums.push_back(3), what will be returned by nums.size()?
Q2
Construct the <code>make_even</code> function that loops through vec, adds 1 to any elements that are odd, and returns the new vector.
-
i += 1; } -
vec[i] += 1; } -
} } -
else { #distractor vec[i] -= 1; } -
for (std::size_t i = 0; i < vec.size(); i++) { -
for (std::size_t i = 0; i < vec.size(); i++) { -
if (i % 2 == 1) { -
if (vec[i] % 2 == 1) { -
return vec; -
vector<int> make_even(vector<int> vec) { -
void make_even(vector<int> vec) {
Q3
What does the following code print?
1vector<int> numbers(5);
2int size = 5;
3for (int i = 0; i < size; i++){
4 numbers[i] = i;
5}
6
7int end = 4;
8
9for (int i = 0; i < size; i++){
10 numbers[i] = numbers[end];
11 end--;
12}
13
14for (int i = 0; i < size; i++){
15 cout << numbers[i] << " ";
16}
17
18cout << '\n';