10.6. Vector functionsΒΆ

The best feature of a vector is its resizeability. 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 he inputs -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.


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>
using namespace std;

int main() {
  vector<int> values;
  int c, i, len;
  cin >> c;

  while (c != -1) {
    cin >> c;
  len = values.size();
  for (i = 0; i < len; i++) {
    cout << values[i] << endl;

The active code below uses the push_back function to add even numbers less than or equal to 10 to the vector values.

Construct the make_even function that loops through vec, adds 1 to any elements that are odd, and returns the new vector.

You have attempted of activities on this page