You are on page 1of 59

vector

class template
<vector>

Vector

Vectors are a kind of sequence containers. As such, their elements are ordered following a strict
linear sequence.

Vector containers are implemented as dynamic arrays; Just as regular arrays, vector containers have
their elements stored in contiguous storage locations, which means that their elements can be
accessed not only using iterators but also using offsets on regular pointers to elements.

But unlike regular arrays, storage in vectors is handled automatically, allowing it to be expanded and
contracted as needed.

Vectors are good at:

 Accessing individual elements by their position index (constant time).
 Iterating over the elements in any order (linear time).
 Add and remove elements from its end (constant amortized time).

Compared to arrays, they provide almost the same performance for these tasks, plus they have the
ability to be easily resized. Although, they usually consume more memory than arrays when their
capacity is handled automatically (this is in order to accomodate for extra storage space for future
growth).

Compared to the other base standard sequence containers (deques and lists), vectors are generally
the most efficient in time for accessing elements and to add or remove elements from the end of the
sequence. For operations that involve inserting or removing elements at positions other than the end,
they perform worse than deques andlists, and have less consistent iterators and references than lists.

Internally, vectors -like all containers- have a size, which represents the amount of elements
contained in the vector. But vectors, also have a capacity, which determines the amount of storage
space they have allocated, and which can be either equal or greater than the actual size. The extra
amount of storage allocated is not used, but is reserved for the vector to be used in the case it
grows. This way, the vector does not have to reallocate storage on each occasion it grows, but only
when this extra space is exhausted and a new element is inserted (which should only happen in
logarithmic frequence in relation with its size).

Reallocations may be a costly operation in terms of performance, since they generally involve the
entire storage space used by the vector to be copied to a new location. Therefore, whenever large
increases in size are planned for a vector, it is recommended to explicitly indicate a capacity for the
vector using member functionvector::reserve.

In their implementation in the C++ Standard Template Library vectors take two template
parameters:

template < class T, class Allocator = allocator<T> > class vector;

Where the template parameters have the following meanings:

 T: Type of the elements.
 Allocator: Type of the allocator object used to define the storage allocation model. By default,
the allocator class template for type T is used, which defines the simplest memory allocation
model and is value-independent.

In the reference for the vector member functions, these same names are assumed for the template
parameters.

Member functions
(constructor) Construct vector (public member function)
(destructor) Vector destructor (public member function)
operator= Copy vector content (public member function)

Iterators:

begin Return iterator to beginning (public member type)
end Return iterator to end (public member function)
rbegin Return reverse iterator to reverse beginning (public member function)
rend Return reverse iterator to reverse end (public member function)

Capacity:

size Return size (public member function)
max_size Return maximum size (public member function)
resize Change size (public member function)
capacity Return size of allocated storage capacity (public member function)
empty Test whether vector is empty (public member function)
reserve Request a change in capacity (public member function)

Element access:

operator[] Access element (public member function)
at Access element (public member function)
front Access first element (public member function)
back Access last element (public member function)

Modifiers:

assign Assign vector content (public member function)
push_back Add element at the end (public member function)
pop_back Delete last element (public member function)
insert Insert elements (public member function)
erase Erase elements (public member function)
swap Swap content (public member function)
clear Clear content (public member function)

Allocator:

get_allocator Get allocator (public member function)

Member types
of template <class T, class Allocator=allocator<T> > class vector;

member type definition
reference Allocator::reference
const_reference Allocator::const_reference
iterator Random access iterator
const_iterator Constant random access iterator
size_type Unsigned integral type (usually same as size_t)
difference_type Signed integral type (usually same as ptrdiff_t)
value_type T
allocator_type Allocator
pointer Allocator::pointer
const_pointer Allocator::const_pointer
reverse_iterator reverse_iterator<iterator>
const_reverse_iterator reverse_iterator<const_iterator>

Vector specialization: vector<bool>

The vector class template has a special template specialization for the bool type.

This specialization is provided to optimize for space allocation: In this template specialization, each
element occupies only one bit (which is eight times less than the smallest type in C++: char).

The references to elements of a bool vector returned by the vector members are not references
to bool objects, but a special member type which is a reference to a single bit, defined inside
the vector<bool> class specialization as:

1 class vector<bool>::reference {
2 friend class vector;
3 reference(); // no public constructor
4 public:
5 ~reference();
6 operator bool () const; // convert to bool
7 reference& operator= ( const bool x ); // assign from bool
8 reference& operator= ( const reference& x ); // assign from bit
9 void flip(); // flip bit value.
10 }

For a similar container class to contain bits, but with a fixed size, see bitset.

vector::vector
public member function
<vector>
explicit vector ( const Allocator& = Allocator() );
explicit vector ( size_type n, const T& value= T(), const Allocator& = Allocator() );
template <class InputIterator>
vector ( InputIterator first, InputIterator last, const Allocator& = Allocator() );
vector ( const vector<T,Allocator>& x );

Construct vector

Constructs a vector container object, initializing its contents depending on the constructor version
used:

explicit vector ( const Allocator& = Allocator() );
Default constructor: constructs an empty vector, with no content and a size of zero.
explicit vector ( size_type n, const T& value= T(), const Allocator& = Allocator() );
Repetitive sequence constructor: Initializes the vector with its content set to a
repetition, n times, of copies of value.
template <class InputIterator> vector ( InputIterator first, InputIterator last, const Allocator& =
Allocator() );
Iteration constructor: Iterates between first and last, setting a copy of each of the sequence of
elements as the content of the container.
vector ( const vector<T,Allocator>& x );
Copy constructor: The vector is initialized to have the same contents (copies) and properties as
vector x.

Parameters
n
Times that value is repeated to form the content of the container object.
Member type size_type is an unsigned integral type.
value
Value to be repeated n times as the content of the container object.
T is the first class template parameter (the type of the elements stored in the vector).
first, last
Input iterators to the initial and final positions in a sequence. The range used is [first,last),
which includes all the elements between first and last, including the element pointed
by first but not the element pointed by last.
The function template type can be any type of input iterator.
x
Another vector object with the same class template parameters (T and Allocator).
unnamed Allocator parameter
Allocator object to be used instead of constructing a new one.
For class instantiations using their version of the default allocator class template, this
parameter is not relevant.

Example
1 // constructing vectors
2 #include <iostream>
3 #include <vector>
4 using namespace std;
5
6 int main ()
7 {
8 unsigned int i;
9
10 // constructors used in the same order as described above:
11 vector<int> first; // empty vector of ints
12 vector<int> second (4,100); // four ints with value 100
13 vector<int> third (second.begin(),second.end()); // iterating through second
14 vector<int> fourth (third); // a copy of third
15
16 // the iterator constructor can also be used to construct from arrays:
17 int myints[] = {16,2,77,29};
18 vector<int> fifth (myints, myints + sizeof(myints) / sizeof(int) );
19
20 cout << "The contents of fifth are:";
21 for (i=0; i < fifth.size(); i++)
22 cout << " " << fifth[i];
23
24 cout << endl;
25
26 return 0;
27 }

Output:

The contents of fifth are: 16 2 77 29

Complexity
For the default constructor, constant.
For the repetitive sequence constructor, linear on n (copy constructions).
For the iterator constructor, linear on the distance between the iterators (copy constructions). If the
iterators are forward, bidirectional or random-access, the capacity is determined before beginning,
otherwise logarithmic complexity (object reallocations) must be added on top of that.
For the copy constructor, linear on x's size (copy constructions).

vector::~vector
public member function
~vector ( );

Vector destructor

Destructs the container object. This calls each of the contained element's destructors, and deallocates
all the storage capacity allocated by the vector.

Complexity
Linear on vector::size (destructors).

10 11 second=first.size()) << endl. Copy vector content Assigns a copy of vector x as the new content for the vector object. 13 14 cout << "Size of first: " << int (first. Then. And then. After a call to this member function. both the vector object and vector x will have the same size and compare equal to each other. 9 vector<int> second (5.vector::operator= public member function vector<T.0). The elements contained in the vector object before the call are dropped.size()) << endl. first is assigned to a newly constructed empty object. Output: Size of first: 0 Size of second: 3 Complexity Linear on sizes (destruction. so both are now equal and with a size of 3. so its size is finally 0. Parameters x A vector object containing elements of the same type. 17 } Both vectors of int elements are initialized to sequences of zeros of different sizes. second is assigned to first. 16 return 0. . copy construction). 15 cout << "Size of second: " << int (second. if any. 12 first=vector<int>().Allocator>& operator= (const vector<T. 5 6 int main () 7 { 8 vector<int> first (3. and replaced by copies of those in vector x. Return value *this Example 1 // vector assignment 2 #include <iostream> 3 #include <vector> 4 using namespace std.0).Allocator>& x).

const_iterator begin () const. i<=5. 12 13 cout << "myvector contains:". 9 for (int i=1.vector::begin public member type iterator begin (). Example 1 // vector::begin 2 #include <iostream> 3 #include <vector> 4 using namespace std.end(). it++ ) 15 cout << " " << *it. 16 17 cout << endl. Both iterator and const_iterator are member types. 5 6 int main () 7 { 8 vector<int> myvector. these are random access iterators. 18 19 return 0. 20 } Output: myvector contains: 1 2 3 4 5 Complexity Constant. Parameters none Return Value An iterator to the beginning of the sequence. which returns a reference to the first element. i++) myvector. 10 11 vector<int>::iterator it. it < myvector. In the vector class template. Return iterator to beginning Returns an iterator referring to the first element in the vector container. this function returns a random access iterator. . 14 for ( it=myvector.push_back(i). Notice that unlike member vector::front.begin() .

i++) myvector. 15 16 cout << endl. const_iterator end () const.insert(myvector. i<=5.end(). 12 vector<int>::iterator it. 17 18 return 0. it < myvector. . these are random access iterators.begin() . Parameters none Return Value An iterator to the element past the end of the sequence. 19 } Output: myvector contains: 1 2 3 4 5 Complexity Constant. 5 6 int main () 7 { 8 vector<int> myvector. this function returns a random access iterator. 13 for ( it=myvector. Notice that unlike member vector::back. Return iterator to end Returns an iterator referring to the past-the-end element in the vector container. In the vector class template. 10 11 cout << "myvector contains:". Example 1 // vector::end 2 #include <iostream> 3 #include <vector> 4 using namespace std. which returns a reference to the element preceding this one.end().i).vector::end public member function iterator end (). 9 for (int i=1. Both iterator and const_iterator are member types. it++ ) 14 cout << " " << *it.

10 11 cout << "myvector contains:". In the vector class template. 19 } Notice how the reverse iterator iterates through the vector in a reverse way by increasing the iterator. Notice that unlike member vector::back. 5 6 int main () 7 { 8 vector<int> myvector. 13 for ( rit=myvector. Example 1 // vector::rbegin/rend 2 #include <iostream> 3 #include <vector> 4 using namespace std. Both reverse_iterator and const_reverse_iterator are member types. this function returns a reverse random access iterator. Output: myvector contains: 5 4 3 2 1 Complexity Constant. rit < myvector. Return reverse iterator to reverse beginning Returns a reverse iterator referring to the last element in the vector container. ++rit ) 14 cout << " " << *rit. defined asreverse_iterator<iterator> and reverse_iterator<const_iterator> respectively.rbegin() .vector::rbegin public member function reverse_iterator rbegin(). which returns a reference to this same element. i++) myvector. const_reverse_iterator rbegin() const. 12 vector<int>::reverse_iterator rit. rbegin refers to the element right before the one that would be referred to by member end. . 9 for (int i=1.rend(). 15 16 cout << endl. Parameters none Return Value A reverse iterator to the reverse beginning of the sequence. 17 18 return 0. i<=5.push_back(i). these are reverse random access iterators.

13 for ( rit=myvector. Example 1 // vector::rbegin/rend 2 #include <iostream> 3 #include <vector> 4 using namespace std. const_reverse_iterator rend() const. rend refers to the character right before the one that would be referred to by member begin. defined asreverse_iterator<iterator> and reverse_iterator<const_iterator> respectively. .vector::rend public member function reverse_iterator rend(). Return reverse iterator to reverse end Returns a reverse iterator referring to the element right before the first element in the vector. 17 18 return 0. ++rit ) 14 cout << " " << *rit. 10 11 cout << "myvector contains:". 19 } Notice how the reverse iterator iterates through the vector in a reverse way by increasing the iterator. Parameters none Return Value A reverse iterator to the reverse end of the sequence. Output: 5 4 3 2 1 Complexity Constant. i<=5. Both reverse_iterator and const_reverse_iterator are member types. which is considered its reverse end. 15 16 cout << endl. In the vector class template. 5 6 int main () 7 { 8 vector<int> myvector. 12 vector<int>::reverse_iterator rit. rit < myvector. i++) myvector. 9 for (int i=1. these are reverse random access iterators.rend().rbegin() .push_back(i).

size: 0 1. 5 6 int main () 7 { 8 vector<int> myints.size() << endl. Vectors automatically reallocate their storage space when needed or when requested with member resize. 19 20 return 0. Return size Returns the number of elements in the vector container.size() << endl.100). size: " << (int) myints. size: 10 2.vector::size public member function size_type size() const.end(). size: " << (int) myints.10.insert (myints.pop_back(). 10 11 for (int i=0. size: 20 3. To retrieve the current storage capacity of a vector you can call to its member capacity.size() << endl. . i<10. 12 cout << "1. 18 cout << "3. 9 cout << "0. 15 cout << "2. Member type size_type is an unsigned integral type. i++) myints.size() << endl. size: 19 Complexity Constant. which is not necessarily equal to its storage capacity.push_back(i). 16 17 myints. 13 14 myints. size: " << (int) myints. Parameters none Return Value The number of elements that conform the vector's content. This is the number of actual objects held in the vector. 21 } Output: 0. size: " << (int) myints. Example 1 // vector::size 2 #include <iostream> 3 #include <vector> 4 using namespace std.

15 cout << "max_size: " << (int) myvector. . but the maximum potential size the vector could reach due to system or library implementation limitations. 9 10 // set some content in the vector: 11 for (int i=0. capacity and max_size 2 #include <iostream> 3 #include <vector> 4 using namespace std. i<100. 17 } A possible output for this program could be: size: 100 capacity: 141 max_size: 1073741823 Complexity Constant. i++) myvector.max_size() << "\n". 12 13 cout << "size: " << (int) myvector. Example 1 // comparing size. Return maximum size Returns the maximum number of elements that the vector container can hold.size() << "\n".push_back(i). This is not the amount of storage space currently allocated to the vector (this can be obtained with member vector::capacity).capacity() << "\n".vector::max_size public member function size_type max_size () const. 5 6 int main () 7 { 8 vector<int> myvector. Member type size_type is an unsigned integral type. Parameters none Return Value The maximum number of elements a vector object can have as its content. 14 cout << "capacity: " << (int) myvector. 16 return 0.

Return Value none If a reallocation happens. which may throw exceptions (for the default allocator. it is performed using Allocator::allocate(). c Object whose content is copied to the added elements in case that sz is greater than the current vector size. This may cause a reallocation. bad_alloc is thrown if the allocation request does not succeed). the rest being dropped. use vector::reserve instead. . Member type size_type is an unsigned integral type. If sz is greater than the current vector size.vector::resize public member function void resize ( size_type sz. T c = T() ). the content is reduced to its first sz elements. T is the first template parameter (the type of the elements stored in the vector). the content is expanded by inserting at the end as many copies of c as needed to reach a size of sz elements. To direct a change only in storage capacity. Notice that this function changes the actual content of the vector by inserting or erasing elements from the vector. It does not only change its storage capacity. the default constructor is used. If not specified. Parameters sz New vector size. expressed in elements. Change size Resizes the vector to contain sz elements. If sz is smaller than the current vector size.

Output: myvector contains: 1 2 3 4 5 100 100 100 0 0 0 0 Complexity Linear on the number of elements inserted/erased (constructions/destructions). 5 6 int main () 7 { 8 vector<int> myvector.resize(12).resize(5). It then uses resize first to trim the vector to a size of 5.i<myvector. 16 myvector. 9 10 unsigned int i.i++) 21 cout << " " << myvector[i].resize(8.Example 1 // resizing vector 2 #include <iostream> 3 #include <vector> 4 using namespace std. 17 myvector. 14 15 myvector. 18 19 cout << "myvector contains:".push_back(i). 11 12 // set some initial content: 13 for (i=1.i<10. and finally it extends its size to 12 with their default values (for int elements this is zero). . 20 for (i=0.size(). 26 } The code sets a sequence of 9 numbers as an initial content for myvector.100). 22 23 cout << endl. then to extend its size to 8 with values of 100 for its new elements.i++) myvector. 24 25 return 0.

the capacity is not necessarily equal to the number of elements that conform the underlying vector content (this can be obtained with membervector::size).push_back(i). or can even be explicitly modified by calling member vector::reserve. Member type size_type is an unsigned integral type. 15 cout << "max_size: " << (int) myvector. which is either equal or greater than the content size. Notice that. If more space is required to accomodate new elements in the vector. measured in the number elements it could hold.vector::capacity public member function size_type capacity () const. 12 13 cout << "size: " << (int) myvector. in vectors. 17 } A possible output for this program could be: size: 100 capacity: 141 max_size: 1073741823 Complexity Constant. i<100. 9 10 // set some content in the vector: 11 for (int i=0.size() << "\n". Notice also that this capacity does not suppose a limit to the size of the vector. capacity and max_size 2 #include <iostream> 3 #include <vector> 4 using namespace std. i++) myvector. 5 6 int main () 7 { 8 vector<int> myvector. Parameters none Return Value The size of the currently allocated storage capacity in the vector. Return size of allocated storage capacity Returns the size of the allocated storage space for the elements of the vector container. Example 1 // comparing size. 14 cout << "capacity: " << (int) myvector.max_size() << "\n". The real limit on the size a vector object can reach is returned by member vector::max_size.capacity() << "\n". . 16 return 0. the capacity is automatically expanded. but the capacity of the actual allocated space.

e. 16 myvector.i++) myvector. Test whether vector is empty Returns whether the vector container is empty. To clear the content of a vector.empty()) 14 { 15 sum += myvector. Output: total: 55 Complexity Constant.vector::empty public member function bool empty () const. 20 21 return 0. Parameters none Return Value true if the vector size is 0.back().push_back(i). 22 } The example initializes the content of the vector to a sequence of numbers (form 1 to 10). . false otherwise. It then pops the elements one by one until it is empty and calculates their sum. 5 6 int main () 7 { 8 vector<int> myvector. This function does not modify the content of the vector in any way. 9 int sum (0). whether its size is 0. use vector::clear. 17 } 18 19 cout << "total: " << sum << endl.i<=10.pop_back(). 12 13 while (!myvector. i. Example 1 // vector::empty 2 #include <iostream> 3 #include <vector> 4 using namespace std. 10 11 for (int i=1.

Request a change in capacity Requests that the capacity of the allocated storage space for the elements of the vector container be at least enough to hold n elements. nor the vector size (for that purposes. bad_alloc is thrown if the allocation request does not succeed). In any case. a call to this function never affects the elements contained in the vector. references and pointers to elements of the vector. Parameters n Minimum amount desired as capacity of allocated storage. see vector::resize or vector::erase. although notice that the parameter n informs of a minimum. which modify the vector size and content). Return Value none If the requested size to allocate is greater than the maximum size (vector::max_size) a length_error exception is thrown. A reallocation invalidates all previously obtained iterators. This informs the vector of a planned increase in size. If successful. which may throw its own exceptions (for the default allocator. In case of reallocation.vector::reserve public member function void reserve ( size_type n ). a reallocation is attempted during the call to this function. Member type size_type is an unsigned integral type. it grants that no further automatic reallocations will happen because of a call to vector::insert or vector::push_back until the vector size surpasses at least n (this preserves the validity of iterators on all these future calls). so the resulting capacity may be any capacity equal or larger than this. When n is greater than the current capacity. . this is performed using Allocator::allocate().

eof()) 21 { 22 content.get() ).ios::in|ios::ate|ios::binary). which is then read character by character (each character stored as an element in the vector). 16 17 content. 10 size_t filesize.is_open()) 14 { 15 filesize=file. 27 for (it=content. 13 if (file. 23 } 24 25 // print out content: 26 vector<int>::iterator it.tellg(). 11 12 ifstream file ("test. 20 while (!file.Example 1 // vector::reserve 2 #include <iostream> 3 #include <fstream> 4 #include <vector> 5 using namespace std.end() .push_back( file.reserve(filesize). . 18 19 file. we avoid all the automatic reallocations that the object content could suffer each time that a new element surpassed the size of its previously allocated storage space.seekg(0). it++) 28 cout << hex << *it. it<content. Complexity Linear at most. 6 7 int main () 8 { 9 vector<int> content. 32 } This example reserves enough capacity in a vector of ints to store the content of an entire file. By reserving a capacity for the vector of at least the size of the entire file.begin() .bin". 29 } 30 31 return 0.

vector::operator[] public member function reference operator[] ( size_type n ). vector::at. 5 int main () 6 { 7 vector<int> myvector (10). 11 12 // assign some values: 13 for (i=0. i++) 25 cout << " " << myvector[i]. // 10 zero-initialized elements 8 unsigned int i. i<sz. Notice that the first element has a position of 0. 9 10 vector<int>::size_type sz = myvector. except that vector::at signals if the requested position is out of range by throwing an exception. A similar member function. i<sz/2. Example 1 // vector::operator[] 2 #include <iostream> 3 #include <vector> 4 using namespace std. 22 } 23 cout << "myvector contains:". i++) 17 { 18 int temp. 21 myvector[i]=temp. 20 myvector[sz-1-i]=myvector[i]. 29 } Output: myvector contains: 9 8 7 6 5 4 3 2 1 0 Complexity Constant. . 24 for (i=0. Return value The element at the specified position in the vector. Member types reference and const_reference are the reference types to the elements of the vector container (generally defined as T& and const T& respectively in most storage allocation models).size(). 28 return 0. i<sz. Access element Returns a reference to the element at position n in the vector container. i++) myvector[i]=i. not 1. 19 temp = myvector[sz-1-i]. const_reference operator[] ( size_type n ) const. has the same behavior as this operator function. Member type size_type is an unsigned integral type. 14 15 // reverse vector using operator[]: 16 for (i=0. Parameters n Position of an element in the vector. 26 27 cout << endl.

Notice that the first element has a position of 0.vector::at public member function const_reference at ( size_type n ) const.size().size(). i<myvector.at(i). Member types reference and const_reference are the reference types to the elements of the vector container (for the default storage allocation model. 18 cout << endl. 19 return 0. 5 6 int main () 7 { 8 vector<int> myvector (10). If this is greater than or equal to the vector size. i++) 17 cout << " " << myvector. i<myvector. reference at ( size_type n ). 14 15 cout << "myvector contains:". i++) 13 myvector. Member type size_type is an unsigned integral type. allocator. Access element Returns a reference to the element at position n in the vector. not 1. The difference between this member function and member operator function operator[] is that vector::at signals if the requested position is out of range by throwing anout_of_range exception. // 10 zero-initialized ints 9 unsigned int i. 10 11 // assign some values: 12 for (i=0. . these are T& and const T& respectively). Return value The element at the specified position in the vector. Parameters n Position of an element in the vector. an exception of type out_of_range is thrown. 20 } Output: myvector contains: 0 1 2 3 4 5 6 7 8 9 Complexity Constant. Example 1 // vector::at 2 #include <iostream> 3 #include <vector> 4 using namespace std.at(i)=i. 16 for (i=0.

front() -= myvector. these are T& and const T& respectively). Member types reference and const_reference are the reference types to the elements of the vector container (for the default storage allocation model. 16 17 cout << "myvector. Access first element Returns a reference to the first element in the vector container. 9 10 myvector. .front() << endl. this function returns a direct reference.push_back(16). Unlike member vector::begin. 5 6 int main () 7 { 8 vector<int> myvector. Example 1 // vector::front 2 #include <iostream> 3 #include <vector> 4 using namespace std.back(). and back 16 14 15 myvector. 11 myvector.front() is now " << myvector.push_back(77). 18 19 return 0. which returns an iterator to this same element. 12 13 // now front equals 77.vector::front public member function reference front ( ). 20 } Output: myvector.front() is now 61 Complexity Constant. const_reference front ( ) const. Parameters none Return value A reference to the first element in the vector. allocator.

Parameters none Return value A reference to the last element in the vector.push_back ( myvector.size() . i<myvector. 9 10 myvector.push_back(10). 24 } Output: myvector contains: 10 9 8 7 6 5 4 3 2 1 0 Complexity Constant. const_reference back ( ) const.back() != 0) 13 { 14 myvector. Example 1 // vector::back 2 #include <iostream> 3 #include <vector> 4 using namespace std. allocator.vector::back public member function reference back ( ). Member types reference and const_reference are the reference types to the elements of the vector container (for the default storage allocation model. this function returns a direct reference. i++) 19 cout << " " << myvector[i]. Unlike member vector::end. 5 6 int main () 7 { 8 vector<int> myvector.back() -1 ). these are T& and const T& respectively). 20 21 cout << endl. which returns an iterator just past this element. 11 12 while (myvector. . 22 23 return 0. Access last element Returns a reference to the last element in the vector container. 18 for (unsigned i=0. 15 } 16 17 cout << "myvector contains:".

9 vector<int> second. 20 cout << "Size of first: " << int (first. 15 16 second. 21 cout << "Size of second: " << int (second. 14 it=first. void assign ( size_type n. 19 third.end()-1). last Input iterators to the initial and final positions in a sequence. // a repetition 7 times of value 100 13 vector<int>::iterator it. 22 cout << "Size of third: " << int (third.assign (7.myints+3).last)). // assigning from array. the new content is the repetition n times of copies of element u. 5 6 int main () 7 { 8 vector<int> first. Parameters first.size()) << endl. u Value to be repeated n times as the new content of the object. Assign vector content Assigns new content to the vector object. including the element pointed by first but not the element pointed by last.last). which includes all the elements between first and last.vector::assign public member function template <class InputIterator> void assign ( InputIterator first. 10 vector<int> third. n Times that u is repeated to form the new content of the object. The range used is [first. T is the first class template parameter (the type of the elements stored in the vector).assign (it. Return value none Example 1 // vector assign 2 #include <iostream> 3 #include <vector> 4 using namespace std. 11 12 first. const T& u ).first.size()) << endl. the new contents are a copy of the elements in the sequence between first and last (in the range [first. 23 return 0.begin()+1.4}. // the 5 central values of first 17 18 int myints[] = {1776. The template type can be any type of input iterator. InputIterator last ). In the second version. dropping all the elements contained in the vector before the call and replacing them by those specified by the parameters: In the first version (with iterators). Member type size_type is an unsigned integral type.assign (myints. 24 } .7.100).size()) << endl.

Add element at the end Adds a new element at the end of the vector. otherwise logarithmic complexity (object reallocations) must be added on top of that. references and pointers. Reallocations invalidate all previously obtained iterators. bidirectional or random-access. the new capacity is determined before beginning. Parameters x Value to be copied to the new element. This effectively increases the vector size by one. In the case of the iteration version. T is the first template parameter (the type of the elements stored in the vector). if the iterators are forward. bad_alloc is thrown if the allocation request does not succeed). vector::push_back public member function void push_back ( const T& x ). which may throw exceptions (for the default allocator. . copy construction).Output: Size of first: 7 Size of second: 5 Size of third: 3 Complexity Linear on initial and final sizes (destruction. after its current last element. The content of this new element is initialized to a copy of x. which causes a reallocation of the internal allocated storage if the vector size was equal to the vector capacity before the call. it is performed using Allocator::allocate(). Return value none If a reallocation happens.

reallocation may happen). 10 11 cout << "Please enter some integers (enter 0 to end):\n". 5 6 int main () 7 { 8 vector<int> myvector.size() << " numbers. 19 20 return 0. 12 13 do { 14 cin >> myint. Delete last element Removes the last element in the vector. This calls the removed element's destructor. vector::pop_back public member function void pop_back ( ). Parameters none Return value none . 21 } The example uses push_back to add a new element to the vector each time a new integer is read.\n".Example 1 // vector::push_back 2 #include <iostream> 3 #include <vector> 4 using namespace std. 16 } while (myint). Complexity Constant (amortized time. 9 int myint. 15 myvector. 17 18 cout << "myvector stores " << (int) myvector.push_back (myint). effectively reducing the vector size by one and invalidating all iterators and references to it.

and then inserting the new element(s). const T& x ). 23 } In this example. 11 myvector. 18 } 19 20 cout << "The elements of myvector summed " << sum << endl. Output: The elements of myvector summed 600 Complexity Constant. and only if. 12 myvector. 21 22 return 0.pop_back(). insertions on positions other than the vector end are performed by moving all the elements between position and the end of the vector to their new positions. template <class InputIterator> void insert ( iterator position. 9 int sum (0). 17 myvector. size_type n. 10 myvector. 5 6 int main () 7 { 8 vector<int> myvector. Reallocations in vector containers invalidate all previously obtained iterators.back(). list).empty()) 15 { 16 sum+=myvector. 13 14 while (!myvector. references and pointers. Because vectors keep an array format. InputIterator first.push_back (300).push_back (200). the elements are popped out of the vector after they are added up in the sum.Example 1 // vector::pop_back 2 #include <iostream> 3 #include <vector> 4 using namespace std. void insert ( iterator position. Insert elements The vector is extended by inserting new elements before the element at position. which may not be a method as efficient as the insertion in other kinds of sequence containers (deque. The parameters determine how many elements are inserted and to which values they are initialized: . InputIterator last ). vector::insert public member function iterator insert ( iterator position. This effectively increases the vector size. const T& x ). the new vector size surpases the current vector capacity. which causes an automatic reallocation of the allocated storage space if.push_back (100).

15 16 // "it" no longer valid. 10 11 it = myvector. 24 25 cout << "myvector contains:".insert (it. bad_alloc is thrown if the allocation request does not succeed). last Iterators specifying a range of elements. The template type can be any type of input iterator. n Number of elements to insert. get a new one: 17 it = myvector. they are performed using Allocator::allocate().100). 20 myvector.insert (it+2. If reallocations happen. x Value to be used to initialize the inserted elements. myarray+3). Return value Only the first version returns a value.last) are inserted at position position. 12 it = myvector.begin(). it<myvector.503 }. myarray.400). iterator is a member type.insert (myvector. Notice that the range includes all the elements between first and last. which may throw exceptions (for the default allocator.Parameters position Position in the vector where the new elements are inserted.begin().2. including the element pointed by first but not the one pointed by last. defined as a random access iterator type.end(). Example 1 // inserting into a vector 2 #include <iostream> 3 #include <vector> 4 using namespace std. 9 vector<int>::iterator it.begin(). 200 ).end()). 29 30 return 0. 13 14 myvector.begin().502.300). Copies of the elements in the range [first.insert ( it . 26 for (it=myvector. 5 6 int main () 7 { 8 vector<int> myvector (3. 21 22 int myarray [] = { 501.anothervector.begin(). 28 cout << endl. it++) 27 cout << " " << *it. first. Each element is initialized to the value specified in x. which is an iterator that points to the newly inserted element. T is the first template parameter (the type of the elements stored in the vector). 18 19 vector<int> anothervector (2. 23 myvector. Member type size_type is an unsigned integral type. 31 } Output: myvector contains: 501 502 503 300 300 400 400 200 100 100 100 .anothervector.

If the new vector size cannot be determined beforehand (which happens in the iterator version for input iterators that are neither forward. Because vectors keep an array format. This effectively reduces the vector size by the number of elements removed. which may not be a method as efficient as erasing in other kinds of sequence containers (deque. list). iterator erase ( iterator first. the complexity is proportional to the number of elements inserted times the distance between position and the end of the vector. including the element pointed by first but not the one pointed by last.e. Return value A random access iterator pointing to the new location of the element that followed the last element erased by the function call. erasing on positions other than the vector end also moves all the elements after the segment erased to their new positions. which in vector containers are defined as a random access iterator type. the range includes all the elements between first and last. iterator last ). . linear on the number of elements inserted (copy construction) plus the number of elements between position and the end of the vector (moving). which is the vector end if the operation erased the last element in the sequence. bidirectional nor random-access). position Iterator pointing to a single element to be removed from the vector. i. Parameters All parameters are of member type iterator. Erase elements Removes from the vector container either a single element (position) or a range of elements ([first. vector::erase public member function iterator erase ( iterator position ). first. This invalidates all iterator and references to elements after position or first..last)). last Iterators specifying a range within the vector to be removed: [first. calling each element's destructor before.last).Complexity If the new vector size can be determined beforehand.

16 17 // erase the first 3 elements: 18 myvector.begin()+3).erase (myvector. 24 25 return 0. and the elements of vec are those which were in this.Example 1 // erasing from vector 2 #include <iostream> 3 #include <vector> 4 using namespace std. references and pointers remain valid for the swapped vectors.erase (myvector. and the same behavior. the elements in this container are those which were in vec before the call.size().begin().push_back(i). swap. 26 } Output: myvector contains: 4 5 7 8 9 10 Complexity Linear on the number of elements erased (destructors) plus the number of elements after the last element deleted (moving). Sizes may differ. i++) myvector. 5 6 int main () 7 { 8 unsigned int i. After the call to this member function. 10 11 // set some values (from 1 to 10) 12 for (i=1. vector::swap public member function void swap ( vector<T. Swap content Exchanges the content of the vector by the content of vec. Notice that a global algorithm function exists with this same name. 19 20 cout << "myvector contains:". i++) 22 cout << " " << myvector[i]. i<=10. 21 for (i=0. All iterators.Allocator>& vec ). 13 14 // erase the 6th element 15 myvector. Parameters vec . which is another vector of the same type. 23 cout << endl. 9 vector<unsigned int> myvector.begin()+5).myvector. i<myvector.

200). . i++) cout << " " << first[i]. 19 20 cout << endl. 16 17 cout << "\nsecond contains:". 5 6 main () 7 { 8 unsigned int i.swap(second). i<second. 9 vector<int> first (3. 23 } Output: first contains: 200 200 200 200 200 second contains: 100 100 100 Complexity Constant. i++) cout << " " << second[i]. 15 for (i=0.size(). Another vector container of the same type as this whose content is swapped with that of this container. 21 22 return 0.100).size(). Return value none Example 1 // swap vectors 2 #include <iostream> 3 #include <vector> 4 using namespace std. // three ints with a value of 100 10 vector<int> second (5. i<first. // five ints with a value of 200 11 12 first. 18 for (i=0. 13 14 cout << "first contains:".

i++) cout << " " << myvector[i]. 5 6 int main () 7 { 8 unsigned int i. 23 24 cout << endl. 19 myvector. 12 myvector.push_back (1101). 10 myvector. Parameters none Return value none Example 1 // clearing vectors 2 #include <iostream> 3 #include <vector> 4 using namespace std. 27 } Output: myvector contains: 100 200 300 myvector contains: 1101 2202 Complexity Linear on size (destructors). i<myvector.size(). 22 for (i=0.clear().size(). 11 myvector. 25 26 return 0. 18 myvector. and then they are removed from the vector container.push_back (300).push_back (200). 13 14 cout << "myvector contains:". Clear content All the elements of the vector are dropped: their destructors are called.vector::clear public member function void clear ( ). 16 17 myvector. 20 21 cout << "\nmyvector contains:". 9 vector<int> myvector.push_back (2202). i++) cout << " " << myvector[i]. .push_back (100). leaving the container with a size of 0. i<myvector. 15 for (i=0.

Example 1 // vector::get_allocator 2 #include <iostream> 3 #include <vector> 4 5 using namespace std. 24 25 return 0. i<5. i<5. 12 13 // allocate an array of 5 elements using vector's allocator: 14 p=myvector. Member type allocator_type is defined to the same as the second template parameter used to instantitate this specific vector class (its Allocator type). Parameters none Return Value The allocator. 10 int * p. 15 16 // assign some values to array 17 for (i=0. 21 cout << endl.allocate(5). Get allocator Returns the allocator object used to constuct the vector. 26 } The example shows an elaborate way to allocate memory for an array of ints using the same allocator used by the vector. Output: The allocated array contains: 0 1 2 3 4 Complexity Constant. 18 19 cout << "The allocated array contains:". 22 23 myvector.get_allocator().deallocate(p. i++) p[i]=i. i++) cout << " " << p[i].get_allocator().5). 11 unsigned int i. 6 7 int main () 8 { 9 vector<int> myvector. 20 for (i=0. .vector::get_allocator public member function allocator_type get_allocator() const.

45.80. which contains all the elements betweenfirst and last.12. class Compare> void sort ( RandomAccessIterator first.int j) { return (i<j). Parameters first.33}.last) into ascending order. template <class RandomAccessIterator. The range used is [first. myvector. 6 7 bool myfunction (int i. //(12 26 32 33 45 53 71 80) .begin()+4. returns true if the first argument goes before the second argument in the specific strict weak ordering it defines.53.26.} 11 } myobject. sort function template <algorithm> template <class RandomAccessIterator> void sort ( RandomAccessIterator first. // 32 71 12 45 26 80 53 33 16 vector<int>::iterator it. myvector.begin()+4).begin().71. and comp for the second. including the element pointed by first but not the element pointed by last. taking two values of the same type than those contained in the range. RandomAccessIterator last ).end(). last Random-Access iterators to the initial and final positions of the sequence to be sorted. The elements are compared using operator< for the first version. Elements that would compare equal to each other are not guaranteed to keep their original relative order. //(12 32 45 71)26 80 53 33 20 21 // using function as comp 22 sort (myvector.begin(). and false otherwise. comp Comparison function object that. Sort elements in range Sorts the elements in the range [first. Compare comp ). 15 vector<int> myvector (myints. // 12 32 45 71(26 33 53 80) 23 24 // using object as comp 25 sort (myvector.last). myvector. } 8 9 struct myclass { 10 bool operator() (int i. 12 13 int main () { 14 int myints[] = {32.end(). myobject). 17 18 // using default comparison (operator <): 19 sort (myvector. RandomAccessIterator last. myfunction).int j) { return (i<j). Return value none Example 1 // sort algorithm example 2 #include <iostream> 3 #include <algorithm> 4 #include <vector> 5 using namespace std. myints+8).

and comp for the second. RandomAccessIterator last. like sort. 33 34 return 0. and false otherwise. 35 } Output: myvector contains: 12 26 32 33 45 53 71 80 Complexity Approximately N*logN comparisons on average (where N is last-first).begin(). class Compare> void stable_sort ( RandomAccessIterator first. 31 32 cout << endl. template <class RandomAccessIterator. returns true if the first argument goes before the second argument in the specific strict weak ordering it defines. In the worst case. but stable_sort grants that the relative order of the elements with equivalent values is preserved. The range used is [first. Compare comp ). comp Comparison function object that. taking two values of the same type than those contained in the range. depending on specific sorting algorithm used by library implementation. stable_sort function template <algorithm> template <class RandomAccessIterator> void stable_sort ( RandomAccessIterator first. Return value none . ++it) 30 cout << " " << *it. which contains all the elements betweenfirst and last. Sort elements preserving order of equivalents Sorts the elements in the range [first.end().last). The elements are compared using operator< for the first version. up to N2.26 27 // print out content: 28 cout << "myvector contains:". Parameters first. including the element pointed by first but not the element pointed by last. last Random-Access iterators to the initial and final positions of the sequence to be sorted. 29 for (it=myvector.last) into ascending order. it!=myvector. RandomAccessIterator last ).

62 2. 33 34 return 0.mydoubles+8).assign(mydoubles. 22 for (it=myvector.begin(). it!=myvector. 31 32 cout << endl.32 1. compare_as_ints).14.42 1.67 using 'compare_as_ints' : 1.62.begin(). 21 stable_sort (myvector. ++it) 23 cout << " " << *it.67. 1. 29 for (it=myvector.72. 35 } compare_as_ints is a function that compares only the integral part of the elements. 1.73.73 1. stable_sortpreserves the relative order these had before the sorting. 2.double j) 8 { 9 return (int(i)<int(j)).begin().58}. 10 } 11 12 int main () { 13 double mydoubles[] = {3.41.14 4. 24 25 myvector. Output: using default comparison: 1. elements with the same integral part are considered equivalent.begin().Example 1 // stable_sort example 2 #include <iostream> 3 #include <algorithm> 4 #include <vector> 5 using namespace std. myvector.32 1.14 4.mydoubles+8).73 2. myvector. it!=myvector.assign(mydoubles. 1.72 2.32.end().end(). 26 27 cout << "\nusing 'compare_as_ints' :". . 16 vector<double>::iterator it. 28 stable_sort (myvector. ++it) 30 cout << " " << *it.58 2. 1.67 Complexity Between N*logN and N*(LogN^2) comparisons (where N is last-first).62 1.end()). 17 18 myvector.41 1.58 3. 6 7 bool compare_as_ints (double i.72 3.end(). therefore. 4. 14 15 vector<double> myvector. 19 20 cout << "using default comparison:". 2.

RandomAccessIterator last ).last) that is used as the upper boundary of the elements that are completely sorted. these are not consecutive parameters. middle Random-Access iterator pointing to the element within the range [first. Partially Sort elements in range Rearranges the elements in the range [first. in such a way that the subrange [first. taking two values of the same type than those contained in the range. Notice that in this function.middle) contains the smallest elements of the entire range sorted in ascending order.end) contains the remaining elements without any specific order.last). and the subrange [middle. but the first and third ones. The elements are compared using operator< for the first version. returns true if the first argument goes before the second argument in the specific strict weak ordering it defines.last). including the element pointed by first but not the element pointed by last. and false otherwise. template <class RandomAccessIterator. RandomAccessIterator middle. Parameters first. Return value none . RandomAccessIterator last. and comp for the second. RandomAccessIterator middle. comp Comparison function object that.partial_sort function template <algorithm> template <class RandomAccessIterator> void partial_sort ( RandomAccessIterator first. last Random-Access iterators to the initial and final positions of the sequence to be used. The range used is [first. Compare comp ). class Compare> void partial_sort ( RandomAccessIterator first. which contains all the elements between firstand last.

myfunction).begin().8.6.7.5. 12 vector<int>::iterator it. 16 17 // using function as comp 18 partial_sort (myvector. 6 7 bool myfunction (int i. myvector. 22 for (it=myvector.end()).end(). 26 27 return 0. myvector.end().4. 13 14 // using default comparison (operator <): 15 partial_sort (myvector. 11 vector<int> myvector (myints.int j) { return (i<j). } 8 9 int main () { 10 int myints[] = {9. it!=myvector. 28 } Output: myvector contains: 1 2 3 4 5 9 8 7 6 Complexity Performs approximately (last-first)*log(middle-first) comparisons. myints+9).1}. myvector. 19 20 // print out content: 21 cout << "myvector contains:". myvector. ++it) 23 cout << " " << *it. See also sort Sort elements in range (function template) stable_sort Sort elements preserving order of equivalents (function template) search Find subsequence in range (function template) reverse Reverse range (function template) .2.begin()+5.begin()+5.begin(). 24 25 cout << endl.3.begin().Example 1 // partial_sort example 2 #include <iostream> 3 #include <algorithm> 4 #include <vector> 5 using namespace std.

but the first and third ones. nth Random-Access iterator pointing to the location within the range [first. Notice that in this function. and comp for the second. in such a way that the element at the resulting nth position is the element that would be in that position in a sorted sequence. class Comapre> void nth_element ( RandomAccessIterator first. RandomAccessIterator last. these are not consecutive parameters. The elements are compared using operator< for the first version. Neither the elements preceding it nor the elements following it are granted to be ordered. and false otherwise. with all the elements preceding it being smaller and all the elements following it greater than it. RandomAccessIterator nth. taking two values of the same type than those contained in the range. Parameters first. returns true if the first argument goes before the second argument in the specific strict weak ordering it defines. RandomAccessIterator nth.nth_element function template <algorithm> template <class RandomAccessIterator> void nth_element ( RandomAccessIterator first. RandomAccessIterator last ).last). including the element pointed by first but not the element pointed by last. last Random-Access iterators to the initial and final positions of the sequence to be used. which contains all the elements between firstand last.last) that will have the sorted element. The range used is [first. comp Comparison function object that. Return value none . Sort element in range Rearranges the elements in the range [first. template <class RandomAccessIterator. Compare comp ).last).

begin(). // 1 2 3 4 5 6 7 8 9 15 16 random_shuffle (myvector. 28 29 cout << endl. 17 18 // using default comparison (operator <): 19 nth_element (myvector.begin()+5. i++) myvector. 26 for (it=myvector. myvector.push_back(i). 12 13 // set some values: 14 for (int i=1. myvector. 32 } Possible output: myvector contains: 3 1 4 2 5 6 9 7 8 Complexity On average. myvector. . } 8 9 int main () { 10 vector<int> myvector. myvector. 6 7 bool myfunction (int i.end().begin(). 11 vector<int>::iterator it.end(). 30 31 return 0.Example 1 // nth_element example 2 #include <iostream> 3 #include <algorithm> 4 #include <vector> 5 using namespace std.end()).begin()+5.int j) { return (i<j). myvector.last). i<10. ++it) 27 cout << " " << *it.begin(). 20 21 // using function as comp 22 nth_element (myvector.myfunction). 23 24 // print out content: 25 cout << "myvector contains:". it!=myvector.end()). linear in the number of elements in [first.begin().

. 10 } 11 return (first2!=last2). InputIterator2 last2 ). Compare comp ). InputIterator2 first2. taking two values of the same type than those contained in the range. comp Comparison function object that. first2.last2). InputIterator1 last1. returns true if the first argument is to be considered less than the second argument. InputIterator2 first2. class Compare> bool lexicographical_compare ( InputIterator1 first1. InputIterator2 last2. class InputIterator2. 12 } Lexicographical comparisons of equivalence with a strict weak ordering criterion between two ranges can be achieved by negating two reflexive less-than comparisons:(a==b) implies (!a<b && !a>b). last2 Input iterators to the initial and final positions of the second sequence.last1) compares lexicographically less than the range [first2. template <class InputIterator1. which contains all the elements between first1 and last1. 3 InputIterator2 first2. Lexicographical comparison is used for example to sort words alphabetically in dictionaries (or in the list of algorithms right here on the left). The behavior of this function template is equivalent to: 1 template <class InputIterator1. It involves comparing sequentially the elements that have the same position in both ranges against each other until one element is not equivalent to the other. 9 first1++. The range used is [first2. InputIterator2 last2 ) 4{ 5 while (first1!=last1) 6 { 7 if (*first2<*first1 || first2==last2) return false 8 else if (*first1<*first2) return true. InputIterator1 last1. last1 Input iterators to the initial and final positions of the first sequence. false if either both ranges are entirely equivalent or if is the second that compares less than the first.last1). first2++. including the element pointed by first1 but not the element pointed by last1. The result of comparing these first non-matching elements is the result of the lexicographical comparison. class InputIterator2> 2 bool lexicographical_compare ( InputIterator1 first1. Parameters first1. Lexicographical less-than comparison Returns true if range [first1. InputIterator1 last1. Return value true if the first range compares lexicographically less than than the second. The range used is [first1. class InputIterator2> bool lexicographical_compare ( InputIterator1 first1.lexicographical_compare function template <algorithm> template <class InputIterator1.last2).

second.count2) comparisons or applications of comp (where countX is the distance between firstX and lastX).second. // 5 letters 13 char second[]="apartment".second+9.first+5.Example 1 // lexicographical_compare example 2 #include <iostream> 3 #include <algorithm> 4 #include <cctype> 5 using namespace std. 35 } The default comparison compares plain ASCII character codes. Our mycomp function transforms the letters to lowercase before comparing them. performs 2*min(count1.second+9.first+5)) 20 cout << first << " is greater than " << second << endl.first+5.first. // 9 letters 14 15 cout << "Using default comparison (operator<): ". 26 if (lexicographical_compare(first. } 10 11 int main () { 12 char first[]="Apple". where 'A' (65) compares less than 'a' (97). . 23 24 25 cout << "Using mycomp as comparison object: ".mycomp)) 27 cout << first << " is less than " << second << endl. 28 else 29 if (lexicographical_compare(second.first. so here the first letter not matching is the third ('a' vs 'p'). char c2) 9 { return tolower(c1)<tolower(c2).mycomp)) 30 cout << first << " is greater than " << second << endl.second+9.second+9)) 17 cout << first << " is less than " << second << endl. 16 if (lexicographical_compare(first. 31 else 32 cout << first << " and " << second << " are equivalent\n". 33 34 return 0.first+5. 18 else 19 if (lexicographical_compare(second. 21 else 22 cout << first << " and " << second << " are equivalent\n". 6 7 // a case-insensitive comparison function: 8 bool mycomp (char c1. Output: Using default comparison (operator<): Apple is less than apartment Using mycomp as comparison object: Apple is greater than apartment Complexity At most.

last). Compare comp ). ForwardIterator last ). and false otherwise.*lowest)) for the comp version 8 largest=first. The comparisons are performed using either operator< for the first version. comp Comparison function object that. 5 if (first==last) return last. last Input iterators to the initial and final positions of the sequence to use. orcomp for the second. ForwardIterator last ) 3{ 4 ForwardIterator largest = first. template <class ForwardIterator. Return value Iterator to largest value in the range. 9 return largest. taking two values of the same type than those contained in the range. 10 } Parameters first. Return largest element in range Returns an iterator pointing to the element with the largest value in the range [first.last). including the element pointed by first but not the element pointed by last.max_element function template <algorithm> template <class ForwardIterator> ForwardIterator max_element ( ForwardIterator first. The range used is [first. class Compare> ForwardIterator max_element ( ForwardIterator first. returns true if the first argument is to be considered less than the second argument. which contains all the elements between first and last. though). 6 while (++first!=last) 7 if (*largest<*first) // or: if (comp(*largest. The behavior of this function template is equivalent to: 1 template <class ForwardIterator> 2 ForwardIterator max_element ( ForwardIterator first. ForwardIterator last. An element is the largest if it does not compare less than any other element (it may compare equal. .

11 12 int main () { 13 int myints[] = {3.6. .2.5. 25 cout << "The largest element is " << *max_element(myints.9}. 5 6 bool myfn(int i. 17 cout << "The largest element is " << *max_element(myints.myints+7. int j) { return i<j.myfn) << endl.4.myobj) << endl.myfn) << endl. } 7 8 struct myclass { 9 bool operator() (int i. except for first. 14 15 // using default comparison: 16 cout << "The smallest element is " << *min_element(myints. 22 23 // using object myobj as comp: 24 cout << "The smallest element is " << *min_element(myints. Output: The smallest element is 2 The largest element is 9 The smallest element is 2 The largest element is 9 The smallest element is 2 The largest element is 9 Complexity Linear: Performs as many comparisons as the number of elements in [first.myints+7) << endl.int j) { return i<j.myints+7. In this case both have been defined to perform a standard less-than comparison. 18 19 // using function myfn as comp: 20 cout << "The smallest element is " << *min_element(myints. 21 cout << "The largest element is " << *max_element(myints.myints+7) << endl.Example 1 // min_element/max_element 2 #include <iostream> 3 #include <algorithm> 4 using namespace std.myints+7.7. 26 27 return 0. } 10 } myobj. 28 } The example illustrates how the comparison object can be either a function or an object whose class defines the operator() member.last).myobj) << endl.myints+7.

it rearranges the elements as such and returns true. Transform range to next permutation Rearranges the elements in the range [first. A permutation is each one of the N! possible arrangements the elements can take (where N is the number of elements in the range). BidirectionalIterator last. but the lowest possible (sorted in ascending order). Compare comp). returns true if the first argument is to be considered less than the second argument. If the function can determine the next higher permutation. template <class BidirectionalIterator. it rearranges the elements according to the first permutation (sorted in ascending order) and returns false.last). including the element pointed by first but not the element pointed by last. the function returns false to indicate that the arrangement is not greater than the previous. Different permutations can be ordered according on how they compare lexicographicaly to each other.next_permutation function template <algorithm> template <class BidirectionalIterator> bool next_permutation (BidirectionalIterator first. which contains all the elements between first and last. BidirectionalIterator last ). last) into the lexicographically next greater permutation of elements. comp Comparison function object that. or comp for the second. Return value true if the function could rearrange the object as a lexicographicaly greater permutation. The comparisons of individual elements are performed using either operator< for the first version. Parameters first. class Compare> bool next_permutation (BidirectionalIterator first. The first such-sorted possible permutation (the one that would compare lexicographically smaller to all other permutations) is the one which has all its elements sorted in ascending order. taking two values of the same type than those contained in the range. . The range used is [first. If that was not possible (because it is already at the largest). and the largest has all its elements sorted in descending order. Otherwise. last Bidirectional iterators to the initial and final positions of the sequence.

2. . 5 6 int main () { 7 int myints[] = {1. 15 } while ( next_permutation (myints.myints+3) ).myints+3). 12 13 do { 14 cout << myints[0] << " " << myints[1] << " " << myints[2] << endl. performs one half as many swaps as the number of elements in the range. 16 17 return 0. 8 9 cout << "The 3! possible permutations with 3 elements:\n". 18 } Output: 1 2 3 1 3 2 2 1 3 2 3 1 3 1 2 3 2 1 Complexity At most.3}. 10 11 sort (myints.Example 1 // next_permutation 2 #include <iostream> 3 #include <algorithm> 4 using namespace std.

string class <string> String class String objects are a special type of container. Member functions (constructor) Construct string object (constructor member) operator= String assignment (public member function) Iterators: begin Return iterator to beginning (public member function) end Return iterator to end (public member function) rbegin Return reverse iterator to reverse beginning (public member function) rend Return reverse iterator to reverse end (public member function) Capacity: size Return length of string (public member function) length Return length of string (public member function) max_size Return maximum size of string (public member function) resize Resize string (public member function) capacity Return size of allocated storage (public member function) reserve Request a change in capacity (public member function) clear Clear string (public member function) empty Test if string is empty (public member function) Element access: operator[] Get character in string (public member function) at Get character in string (public member function) . defined in <string> as: typedef basic_string<char> string. The string class is an instantiation of the basic_string class template. specifically designed to operate with sequences of characters. C++ string objects belong to a class with many built-in features to operate with strings in a more intuitive way and with some additional useful features common to C++ containers. which are mere sequences of characters in a memory array. Unlike traditional c-strings.

Notice that a global function with the same name. exists with the same behavior. and the contents of str are those which were in this string.Modifiers: operator+= Append to string (public member function) append Append to string (public member function) push_back Append character to string (public member function) assign Assign content to string (public member function) insert Insert into string (public member function) erase Erase characters from string (public member function) replace Replace part of string (public member function) swap Swap contents with another string (public member function) String operations: c_str Get C string equivalent (public member function) data Get string data (public member function) get_allocator Get allocator (public member function) copy Copy sequence of characters from string (public member function) find Find content in string (public member function) rfind Find last occurrence of content in string (public member function) find_first_of Find character in string (public member function) find_last_of Find character in string from the end (public member function) find_first_not_of Find absence of character in string find_last_not_of Find absence of character in string from the end (public member function) substr Generate substring (public member function) compare Compare strings (public member function) string::swap public member function void swap ( string& str ). such that after the call to this member function. . swap. Parameters str a string object to swap its contents with those of the object. the contents of this string are those which were in strbefore the call. Swap contents with another string Swaps the contents of the string with those of string object str. and which acts as a specialization for strings of the algorithm function with the same name.

15 16 cout << " After swap.Return value none Example 1 // swap strings 2 #include <iostream> 3 #include <string> 4 using namespace std. 13 14 seller. 18 19 return 0.Allocator> ) void swap ( basic_string& str ). 20 } Output: Before swap. buyer has " << buyer. buyer has money and seller has goods After swap. 17 cout << " and seller has " << seller << endl.swap (buyer). buyer has " << buyer.traits. 5 6 main () 7 { 8 string buyer ("money"). buyer has goods and seller has money Basic template member declaration ( basic_string<charT. . 9 string seller ("goods"). 12 cout << " and seller has " << seller << endl. 10 11 cout << "Before swap.

The first character in the string that compares equal to any of the characters in this sequence is considered a match. A value of 0 means that the entire string is considered. which is indicated by a null-character after the last character. size_t pos = 0 ) const. When pos is specified the search only includes characters on or after position pos. size_t pos. size_t n ) const. Parameters str string containing the characters to search for in the object. size_t find_first_of ( const char* s. To search for an entire sequence of characters use findinstead. If the content is not found. size_t pos = 0 ) const. n Length of sequence of characters to search for. . ignoring any possible occurrences at previous character positions. Notice that for a match to happen it is enough that one of the characters matches in the string (any of them). The first character in the string that compares equal to any of the characters in str is considered a match. Return Value The position of the first occurrence in the string of any of the characters searched for. the number of characters in the sequence of characters to search for is only determined by parameter n. In the second member function version. size_t pos = 0 ) const. c Individual character to be searched for. s Array with a sequence of characters. a null-terminated sequence (c-string) is expected. s or c. and returns the position of the first occurrence in the string. the member value npos is returned. pos Position of the first character in the string to be taken into consideration for possible matches. size_t find_first_of ( const char* s. size_t find_first_of ( char c.string::find_first_of public member function size_t find_first_of ( const string& str. Find character in string Searches the string for any of the characters that are part of either str. In the third version. and the amount of characters to search for is determined by its length.

find_first_of("aeiou".found+1). size_type pos. 7 size_type pos = 0 ) const. 5 size_type n ) const. 6 size_type find_first_of ( const charT* s. 9 size_t found."). 15 found=str. Basic template member declarations ( basic_string<charT. 10 11 found=str. 16 } 17 18 cout << str << endl. 12 while (found!=string::npos) 13 { 14 str[found]='*'.Allocator> ) 1 typedef typename Allocator::size_type size_type. size_type pos = 0 ) const. 21 } R*pl*c* th* v*w*ls *n th*s s*nt*nc* by *st*r*sks.find_first_of("aeiou"). 3 size_type pos = 0 ) const. 8 size_type find_first_of ( charT c.Example 1 // string::find_first_of 2 #include <iostream> 3 #include <string> 4 using namespace std. .traits. 19 20 return 0. 2 size_type find_first_of ( const basic_string& str. 4 size_type find_first_of ( const charT* s. 5 6 int main () 7 { 8 string str ("Replace the vowels in this sentence by asterisks.

pos Position of the first character in the string to be taken into consideration for matches. size_t pos = 0 ) const. which is indicated by a null-character after the last character. The position of first character in the string that does not compare equal to any of the characters in this sequence is returned. n Length of the sequence of characters s.. and returns its position. size_t find_first_not_of ( const char* s.. size_t find_first_not_of ( char c. The function returns the position of the first character in the object that is not c.find_first_not_of("abcdefghijklmnopqrstuvwxyz "). s or c. 5 6 int main () 7 { 8 string str ("look for non-alphabetic characters. the member value npos is returned."). size_t find_first_not_of ( const char* s.string::find_first_not_of size_t find_first_not_of ( const string& str. ignoring any content in the previous character positions. 15 cout << " at position " << int(found) << endl. A value of 0 means that the entire string is considered. In the second member function version. 9 size_t found. size_t pos = 0 ) const. s Array with a sequence of characters. and the amount of characters to match against is determined by its length. . size_t n ) const. c Individual character. Parameters str string containing the characters to match against in the object. When pos is specified the search only includes characters on or after position pos. 12 if (found!=string::npos) 13 { 14 cout << "First non-alphabetic character is " << str[found]. 10 11 found=str. Find absence of character in string Searches for the first character in the object which is not part of either str. the number of characters in the sequence of characters to match against is only determined by parameter n. Example 1 // string::find_first_not_of 2 #include <iostream> 3 #include <string> 4 using namespace std. size_t pos. size_t pos = 0 ) const. Return Value The position of the first character in the object that is not part of characters it is being matched against. a null-terminated sequence (c-string) is expected. In the third version. If no such position is found.

traits. . 6 size_type find_first_not_of ( const charT* s. 8 size_type find_first_not_of ( charT c.16 } 17 18 return 0. size_type pos = 0 ) const. 7 size_type pos = 0 ) const.at position 12 Basic template member declarations ( basic_string<charT.Allocator> ) 1 typedef typename Allocator::size_type size_type. size_type pos. 4 size_type find_first_not_of ( const charT* s. 19 } First non-alphabetic character is . 3 size_type pos = 0 ) const. 5 size_type n ) const. 2 size_type find_first_not_of ( const basic_string& str.

If this value would make the substring to span past the end of the current string content. Parameters pos Position of a character in the current string object to be used as starting character for the substring. If the position passed is past the end of the string. This substring is the character sequence that starts at character position pos and has a length of n characters. // get from "live" to the end 17 18 cout << str2 << ' ' << str3 << endl. n Length of the substring. therefore. when this value is used. 11 size_t pos. 9 // quoting Alfred N. all the characters between pos and the end of the string are used as the initialization substring. 5 6 int main () 7 { 8 string str="We think in generalities. 21 } generalities live in details.12). an out_of_range exception is thrown. size_t n = npos ) const. Return Value A string object containing a substring of the current object. str3. but we live in details. // position of "live" in str 16 str3 = str.substr (pos). Generate substring Returns a string object with its contents initialized to a substring of the current object.string::substr public member function string substr ( size_t pos = 0. only those characters until the end of the string are used. // "generalities" 14 15 pos = str.substr (12. . 12 13 str2 = str. Whitehead 10 string str2. 19 20 return 0. Example 1 // string::substr 2 #include <iostream> 3 #include <string> 4 using namespace std.". npos is a static member constant value with the greatest possible value for an element of type size_t.find("live").

The entire content of str must be matched in some part of the string to be considered a match. Find content in string Searches the string for the content specified in either str. c Individual character to be searched for. the size of the content to be matched is only determined by parameter n. s Array with a sequence of characters. Return Value The position of the first occurrence in the string of the searched content. whenever more than one character is being searched for. size_t pos = 0 ) const. a null-terminated sequence is expected. Parameters str string to be searched for in the object. it is not enough that only one of these characters match. . size_t n ) const. A value of 0 means that the entire string is considered. size_t find ( char c. and returns the position of the first occurrence in the string. size_t find ( const char* s. size_t pos = 0 ) const.string::find public member function size_t find ( const string& str. s or c. size_t find ( const char* s. but the entire sequence of characters to find must be matched. Notice that unlike member find_first_of. When pos is specified the search only includes characters on or after position pos. size_t pos = 0 ) const. In the second member function version. In the third version. pos Position of the first character in the string to be taken into consideration for possible matches. size_t pos. ignoring any possible occurrences in previous locations. therefore its end is determined by the first occurrence of a null character in it. n Length of sequence of characters to search for. If the content is not found. the member value npos is returned.

found+1. 10 size_t found.Example 1 // string::find 2 #include <iostream> 3 #include <string> 4 using namespace std.replace(str. 32 33 return 0.find("haystack"). 31 cout << str << endl. 20 21 found=str. size_type pos = 0 ) const. 24 25 found=str.find('. size_type pos = 0 ) const."preposition"). 5 6 int main () 7 { 8 string str ("There are two needles in this haystack with needles. 22 if (found!=string::npos) 23 cout << "'haystack' also found at: " << int(found) << endl. 26 if (found!=string::npos) 27 cout << "Period found at: " << int(found) << endl. 16 17 found=str.6). size_type pos.length(). 5 size_type find ( charT c."). 3 size_type find ( const charT* s.str2. Basic template member declarations ( basic_string<charT.find("needles are small". 28 29 // let's replace the first needle: 30 str. size_type n ) const.find(str2).traits.'). 11 12 // different member versions of find in the same order as above: 13 found=str. size_type pos = 0 ) const.find(str2). 34 } Notice how parameter pos can be used to search for a second instance of the same search string. 18 if (found!=string::npos) 19 cout << "second 'needle' found at: " << int(found) << endl. 4 size_type find ( const charT* s.Allocator> ) 1 typedef typename Allocator::size_type size_type. Output: first 'needle' found at: 14 second 'needle' found at: 44 'haystack' also found at: 30 Period found at: 51 There are two prepositions in this haystack with needles. . 14 if (found!=string::npos) 15 cout << "first 'needle' found at: " << int(found) << endl. 2 size_type find ( const basic_string& str. 9 string str2 ("needle").

If the position passed is past the end of the string. the function returns *this. Only one character is affected. size_t n = npos ). iterator erase ( iterator position ).string::erase public member function string& erase ( size_t pos = 0. The default value of npos indicates that all the characters until the end of the string should be erased. position Iterator of the member type string::iterator referring to a single character in the string to be removed. For the remaining members. iterator last ). the function returns an iterator of member type string::iterator referring to the character that now occupies the position of the first character erased. last Iterator of the member type string::iterator referring to the last character in the sequence of characters within the string to be erased. first Iterator of the member type string::iterator referring to the first character in a sequence of characters within the string to be erased. The characters affected depend on the member function version used: string& erase ( size_t pos = 0. Notice that both parameters are optional: with only one argument. and with no arguments. an out_of_range exception is thrown. Erase characters from string Erases a part of the string content. Erases all the characters between first and last. size_t n = npos ). iterator last ). It may remove less characters if the end of the string is reached before the n characters have been erased. shortening the length of the string. iterator erase ( iterator position ). returns end(). Return Value For the member that returns a string&. . Erases a sequence of n characters starting at position pos. the function deletes the entire string. or. Parameters pos Position within the string of the first character to be erased. n Amount of characters to be removed. iterator erase ( iterator first. Erases the character referred by the iterator position. if no such character exists. like member clear. iterator erase ( iterator first. the function deletes everything from position pos forwards. size_t is an unsigned integral type.

// "This is an phrase.Allocator> ) 1 typedef typename Allocator::size_type size_type. .8). 20 cout << str << endl. // "This phrase.traits. 3 iterator erase ( iterator p ).begin()+9. 17 cout << str << endl. 4 iterator erase ( iterator first." 14 15 it=str." 18 19 str.erase (str. iterator last ). 22 } Basic template member declaration ( basic_string<charT.begin()+5.Example 1 // string::erase 2 #include <iostream> 3 #include <string> 4 using namespace std. 16 str. 2 basic_string& erase( size_type pos = 0. 5 6 int main () 7 { 8 string str ("This is an example phrase. 9 string::iterator it.")." 21 return 0.erase (10.end()-7). str. // "This is a phrase. 13 cout << str << endl. size_type n = npos).erase (it). 10 11 // erase used in the same order as described above: 12 str.

because the end of the sequence of characters is precisely determined by the first occurrence of a null character. Notice that the first position has also a value of 0. string& replace ( size_t pos1. size_t n1. const char* s ).j2 Iterators referring to the beginning and the end of a sequence of characters whose content is used as replacement. In the third group of member versions. const char* s. n1 Length of the section to be replaced within the string. size_t pos2. size_t n2 ). pos1 Position within the string of the first character of the section to be replaced. iterator i2. n2 Length in characters of the replacement string. If this is longer than the actual length of the string. const string& str.i2 Iterators referring to the beginning and the end of the section in the string to be replaced. size_t n1. Parameters str Another object of class string whose content is entirely or partially used as the replacement. string& replace ( iterator i1. an out_of_range exception is thrown. Notice that the first position has a value of 0. size_t n2. string& replace ( iterator i1.string::replace public member function string& replace ( size_t pos1. c Character value to be used to be repeated n2 times as the replacement content. size_t n1. the function replaces the entire section between pos1 and the end of the string. this does not need to be a null-terminated sequence. size_t n2. string& replace ( iterator i1. iterator i2. template<class InputIterator> string& replace ( iterator i1. const char* s. only the amount of characters until the end of that source is used as replacement. i1. size_t n1. iterator i2. InputIterator j2 ). const string& str ). string& replace ( size_t pos1. pos2 Starting position of the substring of str that has the content to be inserted. not 1. If the position passed is past the end of the string. If the source of characters is not long enough. string& replace ( iterator i1. string& replace ( size_t pos1. string& replace ( size_t pos1. If the position passed is past the end of str. size_t n1. an out_of_range exception is thrown. size_t n2 ). const char* s ). size_t n2 ). iterator i2. . char c ). iterator i2. const string& str ). j1. InputIterator j1. but in the fourth group it does. since its length is determined by parameter n2. s Array with a sequence of characters. char c ).

replace(it.str4." 20 str. 11 string str4="useful.5."replace it".str3.1. // "sample phrase!!!" 26 str.7). 35 } Output: replace is useful.6." 19 str.". // "replace is cooool!!!" 30 it+=3. // ^ 25 str.end()-4.replace(8." 17 str."a short").replace(22.replace(it.6). // "this is just a phrase. // "replace phrase!!!" 27 it+=8. // "this is a short phrase!!!" 22 23 // Using iterators: 0123456789*123456789* 24 string::iterator it = str.str4. // ^ 31 str.replace(it+4. 10 string str3="sample phrase".end().it+6.begin().end()-3.end()). 5 6 int main () 7 { 8 string base="this is a test string. 32 // "replace is useful. // "replace is cool!!!" 29 str. 34 return 0. // "this is a test string.3. // "this is an example phrase. 9 string str2="n example". // "this is a short phrase.10. // ^ 28 str.it+6." 33 cout << str << endl.7." 18 str.6).str.'!').Return Value *this Example 1 // replacing in a string 2 #include <iostream> 3 #include <string> 4 using namespace std.replace(9.6.replace(it.str2)."just all".4.str.". 12 13 // function versions used in the same order as described above: 14 15 // Using positions: 0123456789*123456789*12345 16 string str=base. // "this is an example string.'o'). .str." 21 str.replace(it.replace(8.begin().str3)."is cool").replace(19.