C++ Vectors – std::vector – Containers Library

vectors in C++

Vectors are sequence containers (same as dynamic arrays) which resizes itself automatically. The size changes (i.e. vector can shrink or expand as needed at run time) when an element is inserted or deleted, with their storage being handled automatically by the container.

Just like arrays, vector elements are placed in adjacent memory locations so that they can be accessed and traversed using iterators i.e. subscript operator []. Vector elements can also be accessed by using offsets to regular pointers to elements. This means that a pointer to an element of a vector may be passed to any C++ functions that expect a pointer to an element of an array.

In vectors, data is inserted at the end and inserting data at the end may require extending the array. To support shrink and expand functionality at run-time, vector container may allocate some extra storage to accommodate for possible growth thus container have actual capacity greater than the size.

Therefore, compared to the other dynamic sequence containers (deques, lists and forward_lists) in standard template library (STL), vectors are very efficient accessing its elements (just like arrays) and relatively efficient adding or removing elements from its end. However, vector consumes more memory in exchange for the ability to manage storage and grow dynamically in an efficient way.

The rest of the article is organized as following:

Declaring a Vector in C++
Initializing a Vector in C++
C++ Vector Functions
Traversing C++ Vectors using Iterators
Accessing C++ Vector Elements by using Access Functions
Manipulate Vector Elements by using Modifier Functions
C++ Vector Capacity and Size Functions
When is the vector most efficient in C++?
Zero Sized Vectors

We also developed the following C++ programs to demonstrate different functions of vectors using C++.

C++ Program to Access Vector Elements
C++ Program to Manipulate Vector Elements
C++ Program to display number of elements in a Vector

Declaring a Vector in C++

Below is the C++ definition of std::vector from <vector> header library file

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

Vector Parameters

  • T – The type of elements. T may be substituted by any other data type including user-defined type.
  • Allocator − Type of allocator object. By default, the allocator class template is used, which defines the memory allocation/de-allocation model, construct/destroy elements and is value-independent.

Initializing a Vector in C++

A vector in C++ can be initialized in multiple ways. For example, initialize the vector as a list.

vector<int> my_vector = {1, 2, 3, 4};

Another way is to initialize the vector by assigning the value directly to the vector.

vector<int> my_vector {1, 2, 3, 4};

Another way to initialize the vector to a predefined size with a single value. vector<int> my_vector (3, 4);

Here the vector is defined with the size of 3 elements and all having the value 4, which is equivalent to the following.

vector<int> my_vector = {4, 4, 4};

C++ Vector Functions

Vectors library provides lots of functions to traverse, access and manipulate vectors. There are a lot many helper/utility vector functions to determine the capacity and size of vectors.

Traversing C++ Vectors using Iterators

As vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators. There are four basic functions associated with vectors which are used to traverse vectors i.e.

  • begin() – Returns an iterator pointing to the first element in the vector
  • end() – Returns an iterator pointing to the theoretical element that follows last element in the vector
  • rbegin() – Returns a reverse iterator pointing to the last element in the vector (reverse beginning). It moves from last to first element
  • rend() – Returns a reverse iterator pointing to the theoretical element preceding the first element in the vector (considered as reverse end)

C++ Program to demonstrate Vector Iterators

Consider the following program which demonstrate the use of iterators to access and traverse vector elements using the iterator member types discussed above.

#include <iostream>
#include <vector>

using namespace std;

int main()
{
 vector <int> scores;
 vector <int> :: iterator i;
 vector <int> :: reverse_iterator ri;

 for (int i = 1; i <= 5; i++){
  scores.push_back(i);
 }

 cout << "Output of begin() and end():";
 for (i = scores.begin(); i != scores.end(); ++i){
  cout << ' ' << *i;
 }

 cout << endl << endl;
 cout << "Output of rbegin() and rend():";
 for (ri = scores.rbegin(); ri != scores.rend(); ++ri){
  cout << ' ' << *ri;
 }
 return 0;
}

Output:

Output of begin() and end(): 1 2 3 4 5

Output of rbegin() and rend(): 5 4 3 2 1

Accessing C++ Vector Elements by using Access Functions

Vector elements can be accessed using the following vector functions. Any/combination or all of these functions can be used to access vector elements in different situations.

  • front() – Returns a reference to the first element in the container.
  • back() – Returns reference to the last element in the container.
  • at() – Returns a reference to the element at specific position in the vector by using a reference operator (as mentioned below)
  • Reference Operator [r] – Returns a reference to the element at position ‘r’ in the vector

C++ Program to Access Vector Elements

Consider the following program which demonstrate the access and traverse vector elements using the access functions as discussed above.

#include <iostream>
#include <vector>

using namespace std;
 
int main()
{
    vector <int> ints = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
 
    cout << "Using at() function - Value returned by ints.at(4) = " << ints.at(4);
    cout << endl;
    cout << "Using front() function - Value returned by ints.front() = " << ints.front();
    cout << endl;
    cout << "Using back() function - Value returned by ints.back() = " << ints.back();
    cout << endl;
 cout << "Reference Operator [r] : Value at position ints[2] = " << ints[2];
    cout << endl;
 
    return 0;
} 

Output:

Using at() function - Value returned by ints.at(4) = 5

Using front() function - Value returned by ints.front() = 1

Using back() function - Value returned by ints.back() = 10

Reference Operator [r] : Value at position ints[2] = 3

Manipulate Vector Elements by using Modifier Functions

The following C++ Vector functions are used to interact with vector elements and manipulate them.

  • insert() – Inserts elements into the vector.
  • assign() – Assigns new content to vector and resize
  • emplace() – Constructs element in-place
  • push_back() – Adds an element to the end of the vector and increment the size
  • emplace_back() – Constructs an element in-place at the end
  • pop_back() – Removes the last element of the vector and decrements the size
  • resize() – Changes the number of elements stored
  • swap() – Swaps the contents of two vectors
  • clear() – Clears the contents of the vector
  • erase() – Removes the specific element or range of elements from vector

C++ Program to Manipulate Vector Elements

Consider the following program which demonstrate the manipulation of vector elements using the modified functions as discussed above.

#include <iostream>
#include <vector>

using namespace std;
 
void print_vec(const vector<int>& vec)
{
    for (auto x: vec) {
         cout << ' ' << x;
    }
    cout << '\n';
}
 
int main ()
{
    cout << "Initial Vector:" << endl;
    vector<int> vec(3,100);
    print_vec(vec);
 
    cout << "Insert Value: 200 at the beginning of Vector:" << endl;
    auto it = vec.begin();
    it = vec.insert(it, 200);
    print_vec(vec);
    cout << "Insert Value: 300 twice at the end of Vector:" << endl;
    it = vec.end();
    vec.insert(it,2,300);
    print_vec(vec);
 
}

Output:

Initial Vector:

 100 100 100

Insert Value: 200 at the beginning of Vector:

 200 100 100 100

Insert Value: 300 twice at the end of Vector:

 200 100 100 100 300 300

C++ Vector Capacity and Size Functions

The following C++ Vector functions are used to manipulate vector size and capacity.

  • empty() – This function checks whether the container is empty or not.
  • size() – Returns the number of elements in the vector
  • max_size() – Returns the maximum possible number of elements of vector
  • reserve() – Reserves storage i.e. increase the capacity of the vector to a value that’s greater or equal to new_cap by pre-allocatong the memory.
  • capacity() – Returns the number of elements that can be held in currently allocated storage
  • shrink_to_fit() – Reduces memory usage by freeing unused memory

C++ Program to display number of elements in a Vector

The following C++ program displays the number of elements in vector using size() function.

#include <vector>
#include <iostream>
 
using namespace std;

int main()
{ 
    vector<int> ids {1, 3, 5, 7};
 
    cout << "ids contains " << ids.size() << " elements.\n";
}

Output:

ids contains 4 elements.

When is the vector most efficient in C++?

Vector is more efficient when you reserve() the correct amount of storage at the beginning so the vector never has to reallocate.

Vector is more efficient when you only add and remove elements from the back end.

It is possible to insert and erase elements from the middle of a vector using an iterator, however, when an object is inserted into the vector in the middle, it must push other objects down to maintain the linear array.

Zero Sized Vectors

Zero sized vectors are also possible and valid. In that case vector.begin() and vector.end() points to same location. But behavior of calling front() or back() is undefined.

M. Saqib: Saqib is Master-level Senior Software Engineer with over 14 years of experience in designing and developing large-scale software and web applications. He has more than eight years experience of leading software development teams. Saqib provides consultancy to develop software systems and web services for Fortune 500 companies. He has hands-on experience in C/C++ Java, JavaScript, PHP and .NET Technologies. Saqib owns and write contents on mycplus.com since 2004.
Related Post