push_back in vector in c++ code example

Example 1: java vector push_back

// push_back equivalent
ArrayList<int> a = new ArrayList<int>();
a.add(2);             // Add element to the ArrayList.
a.add(4);

// pop_back equivalent.
a.remove(a.size()-1); // Remove the last element from the ArrayList.

Example 2: back_inserter in vector c++

// back_inserter example
#include <iostream>     // std::cout
#include <iterator>     // std::back_inserter
#include <vector>       // std::vector
#include <algorithm>    // std::copy

int main () {
  std::vector<int> foo,bar;
  for (int i=1; i<=5; i++)
  { foo.push_back(i); bar.push_back(i*10); }

  std::copy (bar.begin(),bar.end(),back_inserter(foo));

  std::cout << "foo contains:";
  for ( std::vector<int>::iterator it = foo.begin(); it!= foo.end(); ++it )
	  std::cout << ' ' << *it;
  std::cout << '\n';

  return 0;
}

Tags:

Cpp Example