![]() |
VOOZH | about |
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"}};
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.
vectorName.push_back({element1, element2});
// or more recommended
vectorName.push_back(make_pair(element1, element2));
The below program demonstrates how we can add an element in a vector of pairs in C++.
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.