C++ Vectors

In this blog post, you will learn C++ vectors with the help of programming examples. This article will be long because I will try to cover most of the important points related to vectors. So hopefully you will love this ultimate Guide to C++ Vector.

So let’s start this article with this question what vectors are in C++?

 

What is a Vector in C++?

Vectors are part of the C++ Standard Template Library (STL). Before using it you need to include the vector header file <vector> in your program.

Now let’s come to the topic of what vector is.

So a vector is a sequence container that stores similar type objects. These elements are stored contiguously, which means that elements can be accessed through iterators and offsets to regular pointers to elements. This means that a pointer to a vector element can be passed to any function that expects a pointer to an array element.

The vector has one more ability that it can grow and shrink dynamically which means storage management is handled automatically.

Note: Vectors support constant time insertions and deletions at the end of the sequence. Inserting or deleting elements in the middle of a vector requires linear time

Syntax:

 

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

Parameters:

Type: The element data type to be stored in the vector.

Allocator:  An allocator that is used to acquire/release memory and to construct/destroy the elements in that memory. This argument is optional and the default value is allocator<T>.

 

Declaration of Vectors in C++:

You must include the header file #include<vector> before using vectors in C++. There are many ways to declare the vector in C++, let’s see a few of them.

vector<Data_Type> vector_name; // Empty Vector

vector<Data_Type> vector_name(size); // Declaration with size

vector<Data_Type> vector_name(size, value); // Declaration with size and value

You can see the above example where each new vector starts with the vector keyword. This is followed by angle brackets that contain the type of data the vector can store like char, int, float,  ..etc. And in the last name of the vector.

Consider the below example for a better understanding.

Example,

#include <iostream>
#include <vector>

using namespace std;



int main()
{
    vector<int> vec1; //empty vector

    //vec2  = {0, 0, 0, 0, 0}
    vector<int> vec2(5); //Default value 0 for each element
    cout<<"Print elements of Second vector"<<endl;
    for(int obj2:vec2)
    {
        cout<< obj2 << " ";
    }

    cout<<"\n\nPrint elements of third vector"<<endl;

    // vec3 = {2, 2, 2, 2, 2} vector is created
    vector<int> vec3(5, 2);
    for(int obj3:vec3)
    {
        cout<< obj3 << " ";
    }

    return 0;
}

Output:

Print elements of Second vector
0 0 0 0 0

Print elements of third vector
2 2 2 2 2

 

Using the above declaration you can also create a multidimensional vector. Let’s consider the example where I am declaring a 2D- vector.

vector<vector<Data_type>> vector_name; //2D vector

Note: 2D- vector means, a vector of a vector.

 

Initialization of Vectors:

You can initialize a vector in different ways let’s see some of the ways to initialize a vector.

Initializing like Arrays:

Like the fixed-size arrays, you can assign values to a vector when it is being declared.

Consider the below example, in which declaration and initialization happen at the same time.

vector<int> vec{ 5, 10, 15 };

 

Initialize a Vector From an Array:

You can initialize a vector from an existing array. See the below pseudo code,

int arr[] = { 5, 10, 15 };

vector<int> vec(begin(arr), end(arr));

 

Initialize a Vector From another Vector:

You can also initialize a vector from another vector using the same concept used for an array. See the below pseudo code,

vector<int> vect1{ 10, 20, 30 };

vector<int> vect2(vect1.begin(), vect1.end());

 

Initialize a Vector in C++ Using the push_back():

Using the push_back() method you can also initialize the vector in C++. Consider the below example code.

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

int main()
{
    vector<int> vec;

    vec.push_back(27);
    vec.push_back(6);
    vec.push_back(8);
    vec.push_back(24);
    vec.push_back(23);

    for (int obj : vec)
        cout << obj << " ";

    return 0;
}

 

Initialize a Vector by Specifying the Size and Value in C++:

You can specify the size and value of a vector during its declaration. Consider the below example code,

vector<int> vec(5, 45);

Here, 5 is the size of the vector and 45 is the value for each.

 

Basic Vector Operations:

In C++, vector class provides many methods to perform different operations on vectors. I will try to mention all important methods of vector class in this blog post and cover each method separately in another blog post.

But here I want to mention some general vector operations which frequently used in programs.

1. Adding Elements to a Vector:

You can add elements in a vector using the vector methods push_back(), insert(), and emplace_back(). Let’s see an example of how you can add an element in a vector by using use the push_back() method.

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

int main()
{
    vector<int> vec {10, 20, 30, 40, 50};

    cout << "Initial Vector: ";

    for (int obj : vec)
    {
        cout << obj << "  ";
    }

    // add the integers 60 and 70 to the vector
    vec.push_back(60);
    vec.push_back(70);

    cout << "\nUpdated Vector: ";

    for (int obj : vec)
    {
        cout << obj << "  ";
    }

    return 0;
}

Output:

Initial Vector: 10  20  30  40  50
Updated Vector: 10  20  30  40  50  60  70

 

You can see in the above example code, that I have added two elements 60 and 70 using the push_back() methods.

 

2. Access Elements of a Vector:

Using the at() method you can access the element from the specified index.  See the below example,

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

int main()
{
    vector<int> vec {10, 20, 30, 40, 50};

    cout << "Element at Index 0: " << vec.at(1) << endl;
    cout << "Element at Index 2: " << vec.at(2) << endl;
    cout << "Element at Index 4: " << vec.at(4);

    return 0;
}

Output:

Element at Index 0: 20
Element at Index 2: 30
Element at Index 4: 50

 

You can also access the vector element using the subscript operator ([]) like the normal array. But I do not suggest that you access the vector element with subscript because it does not give you a warning for boundary error. I advise you to use the at() method to access the element from the specified index because it throws an exception whenever the vector is out of bounds. Let’s understand it with an example code.

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

int main()
{
    vector<int> vec {10, 20, 30, 40, 50};

    cout << "Element at Index 10: " << vec[10] << endl;

    return 0;
}

You will not get the out-of-range error with the above code. But with at() method, you will get the error message see the below code.

 

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

int main()
{
    vector<int> vec {10, 20, 30, 40, 50};

    cout << "Element at Index 10: " << vec.at(10) << endl;

    return 0;
}

Output:

terminate called after throwing an instance of ‘std::out_of_range’
what(): vector::_M_range_check

 

3. Remove Elements from C++ Vectors:

You can remove an element from a vector using the following methods.

  • vector::pop_back()
  • vector::pop_front()
  • vector::erase()
  • vector::clear()
  • remove(first, last, val)
  • remove_if()

Let’s see an example of removing an element using the pop_back() method. The method vector::pop_back() removes the elements stored in a vector one by one from the end.

#include <iostream>
#include <vector>


int main()
{
    std::vector<int> vec{1, 2, 3, 4};

    // initial vector
    std::cout << "Initial Vector: ";
    for (int i : vec)
    {
        std::cout << i << " ";
    }

    // remove the last element
    vec.pop_back();

    // final vector
    std::cout << "\nVector after removing last element: ";
    for (int i : vec)
    {
        std::cout << i << " ";
    }

    return 0;
}

Output:

Initial Vector: 1 2 3 4
Vector after removing last element: 1 2 3

 

4. Change Vector Element:

Using the at() and subscript operator [] you can change an element of the vector. Both return a reference to the indexed element, so you can simply use:

vec.at(index) = value;

  or

vec[index] = value;

 

Consider the below example code for better understanding.

#include <iostream>
#include <vector>


int main()
{
    std::vector<int> vec{1, 2, 3, 4, 5};

    // initial vector
    std::cout << "Initial Vector: \n";
    for (int i : vec)
    {
        std::cout << i << " ";
    }

    // change elements at indexes 0 and 3
    vec.at(0) = 6;
    vec.at(3) = 0;
    // final vector
    std::cout << "\nVector after changing element: \n";
    for (int i : vec)
    {
        std::cout << i << " ";
    }

    return 0;
}

Output:

Initial Vector:
1 2 3 4 5
Vector after changing element:
6 2 3 0 5

 

 

C++ Vector Member Functions:

In C++, the vector class provides various member functions to perform different operations on a vector. I mentioned a few of them.

Member functions:

(constructor)
constructs the vector
(public member function)
(destructor)
destructs the vector
(public member function)
operator=
assigns values to the container
(public member function)
assign
assigns values to the container
(public member function)
assign_range
(C++23)
assigns a range of values to the container
(public member function)
get_allocator
returns the associated allocator
(public member function)

Element access

at
access specified element with bounds checking
(public member function)
operator[]
access specified element
(public member function)
front
access the first element
(public member function)
back
access the last element
(public member function)
data
direct access to the underlying array
(public member function)

Iterators

begin cbegin
(C++11)
returns an iterator to the beginning
(public member function)
end cend
(C++11)
returns an iterator to the end
(public member function)
begin crbegin
(C++11)
returns a reverse iterator to the beginning
(public member function)
rend crend
(C++11)
returns a reverse iterator to the end
(public member function)

Capacity

empty
checks whether the container is empty
(public member function)
size
returns the number of elements
(public member function)
max_size
returns the maximum possible number of elements
(public member function)
reserve
reserves storage
(public member function)
capacity
returns the number of elements that can be held in currently allocated storage
(public member function)
shrink_to_fit
(DR*)
reduces memory usage by freeing unused memory
(public member function)

Modifiers

clear
clears the contents
(public member function)
insert
inserts elements
(public member function)
insert_range
(C++23)
inserts a range of elements
(public member function)
emplace
(C++11)
constructs element in-place
(public member function)
erase
erases elements
(public member function)
push_back
adds an element to the end
(public member function)
emplace_back
(C++11)
constructs an element in-place at the end
(public member function)
append_range
(C++23)
adds a range of elements to the end
(public member function)
pop_back
removes the last element
(public member function)
resize
changes the number of elements stored
(public member function)
swap
swaps the contents
(public member function)

 

Difference Between Vector and Array:

There are the following differences between the array and vector.

Arrays:

  • Arrays are a built-in language construct. Elements are stored at the contiguous memory location. You can access it with an index.
  • Array provides just a contiguous, indexable sequence of elements; no bounds checking.
  • Array are of fixed size; you can’t resize an array in C++ (unless it’s an array of POD and it’s allocated with malloc/new);
  • Array take their storage space depending on the scope where you declare them; Also size must be a compile-time constant unless they are allocated dynamically;
  • You have to explicitly deallocate the dynamically allocated array.
  • You can determine the array size using the sizeof (sizeof(arr)/sizeof(*arr)) but if they are dynamically allocated, you just get a pointer, and you can’t determine their size using the sizeof;
  • Array automatically decays to a pointer in most situations; for example, when passing them to a function array decays to a pointer due to this reason usually have to pass array size explicitly as a separate parameter.
  • You can’t copy/assign an array directly; for example (arr1 = arr2).
  • Array can’t be returned from a function;

std::vector:

  • A vector is a template class; It is a C++ only construct;
  • Vector is implemented as a dynamic array; so it can grow and shrink dynamically;
  • With vector, you don’t need to care about the memory it automatically manages their memory, which is freed on vector destruction;
  • Vector can be passed to/returned from functions (by value);
  • A vector doesn’t decay to pointers, but you can explicitly get a pointer to their data  &vec[0] is guaranteed to work as expected);
  • Unlike array vectors can be copied/assigned (this performs a deep copy of all the stored elements);
  • Unlike an array, a vector always has the information about its capacity and elements that have been stored.
  • Vectors usually occupy more space than static arrays, because more memory is allocated to handle future growth. This way a vector does not need to reallocate each time an element is inserted, but only when the additional memory is exhausted.
  • Vector has different methods to perform different operations. It also takes care of boundary; whenever cross the boundary at() method throw the error.

 

C++ Vector Iterators:

Iterators are used to point at the memory addresses of STL containers. They are a generalization of pointers that allow a C++ program to work with different data structures (for example, containers and ranges) in a uniform manner.

You can create vector iterators with the following syntax,

vector<T>::iterator iteratorName;

For example, if you want to create an iterator for a vector of int types, you need to create an iterator in the following form.

vector<int>::iterator i;

 

In C++20, there are six categories of iterators, according to the operations defined on them: input iterators, output iterators, forward iterators, bidirectional iterators, random access iterators, and contiguous iterators.

Let’s see an example to understand how the iterator works. I will talk about the iterator in detail in my other blog post.

// C++ code to demonstrate the working of
// iterator, begin() and end()
#include<iostream>
#include<iterator> // for iterators
#include<vector> // for vectors

using namespace std;

int main()
{
    vector<int> vec = { 1, 2, 3, 4, 5 };
    /*
     Declaring iterator to a vector
    of int within for loop*/
    cout << "Elements of vector are : ";
    for (vector<int>::iterator ptr = vec.begin(); ptr < vec.end(); ptr++)
    {
        cout << *ptr << " ";
    }

    return 0;
}

Output:

Elements of vector are : 1 2 3 4 5

In the above C++ program, we have declared an int vector iterator ptr in order to use it with the vector vec. Within the for loop, we initialized the iterator to the first element of the vector using the begin() function.

for (vector<int>::iterator ptr = vec.begin(); ptr < vec.end(); ptr++)
{
cout << *ptr << ” “;
}

Now iterate the iterator ptr from the beginning of the vector to the end of the vector using the to print the elements of the vector.

Recommended Articles for you: