cplusplus.com cplusplus.com
cplusplus.com   C++ : Reference : STL Containers : vector : push_back
- -
C++
Information
Documentation
Reference
Articles
Sourcecode
Forum
Reference
C Library
IOstream Library
Strings library
STL Containers
STL Algorithms
STL Containers
bitset
deque
list
map
multimap
multiset
priority_queue
queue
set
stack
vector
vector
comparison operators
vector::vector
vector::~vector
member functions:
· vector::assign
· vector::at
· vector::back
· vector::begin
· vector::capacity
· vector::clear
· vector::empty
· vector::end
· vector::erase
· vector::front
· vector::get_allocator
· vector::insert
· vector::max_size
· vector::operator=
· vector::operator[]
· vector::pop_back
· vector::push_back
· vector::rbegin
· vector::rend
· vector::reserve
· vector::resize
· vector::size
· vector::swap

-

vector::push_back public member function
void push_back ( const T& x );

Add element at the end

Adds a new element at the end of the vector, after its current last element. The content of this new element is initialized to a copy of x.

This effectively increases the vector size by one, which causes a reallocation of the internal allocated storage if the vector size was equal to the vector capacity before the call. Reallocations invalidate all previously obtained iterators, references and pointers.

Parameters

x
Value to be copied to the new element.
T is the first template parameter (the type of the elements stored in the vector).

Return value

none

If a reallocation happens, it is performed using Allocator::allocate(), which may throw exceptions (for the default allocator, bad_alloc is thrown if the allocation request does not succeed).

Example

// vector::push_back
#include <iostream>
#include <vector>
using namespace std;

int main ()
{
  vector<int> myvector;
  int myint;

  cout << "Please enter some integers (enter 0 to end):\n";

  do {
    cin >> myint;
    myvector.push_back (myint);
  } while (myint);

  cout << "myvector stores " << (int) myvector.size() << " numbers.\n";

  return 0;
}
The example uses push_back to add a new element to the vector each time a new integer is read.

Complexity

Constant (amortized time, reallocation may happen).

See also

vector::pop_back Delete last element (public member function)
vector::insert Insert elements (public member function)

© The C++ Resources Network, 2000-2007 - All rights reserved
Spotted an error? - contact us