How to Add Element to Vector of Pairs in C++?

In C++, vectors are dynamic arrays that can grow and shrink in size whereas a pair is a container that can store two data elements or objects. A vector of pairs, therefore, is a dynamic array of pairs. In this article, we will learn how to add an element to a vector of pairs in C++.

Example:

Input:
vector<pair<int, string>> vec = {{1, "Apple"}, {2, "Banana"}};
myPair = {3, "Mango"}

Output:
vec = {{1, "Apple"}, {2, "Banana"}, {3,"Mango"}};

Adding to a Vector of Pairs in C++

We can add an element to a vector of pairs using the vector::std::push_back() function that will append the pair passed inside the function at the end of the vector i.e. after its current last element.

Syntax to Add Element to Vector of Pairs in C++

vectorName.push_back({element1, element2});
// or more recommended
vectorName.push_back(make_pair(element1, element2));

C++ Program to Add Element to Vector of Pairs

The below program demonstrates how we can add an element in a vector of pairs in C++.

C++
// C++ program to illustrate add an element in vector of
// pairs
#include <iostream>
#include <utility>
#include <vector>
using namespace std;

int main()
{
    // creating vector of pair
    vector<pair<int, string> > vec
        = { { 1, "Apple" }, { 2, "Banana" } };

    // Adding new pairs
    vec.push_back({ 3, "Mango" });
    vec.push_back(make_pair(4, "Guava"));

    // Printing updated vector
    cout << "Updated vector of pairs:" << endl << "{";
    for (auto& pair : vec) {
        cout << "{" << pair.first << ", " << pair.second
             << "}";
    }
    cout << "}" << endl;

    return 0;
}

Output
Updated vector of pairs:
{{1, Apple}{2, Banana}{3, Mango}{4, Guava}}

Time Complexity: O(1)
Auxiliary Space: O(n), where n is the total number of pairs added to the vector.