How to Create a Vector of Pairs in C++?
Last Updated :
21 Oct, 2024
In C++, std::pair is the data type that stores the data as keys and values. On the other hand, std::vector is an STL container that stores the collection of data of similar type in the contiguous memory location. In this article, we will learn how to combine these two to create a vector of pairs in C++.
What is Vector of Pairs in C++?
A vector of pairs is a std::vector container in which each element is of std::pair type. In C++, we can create a vector of pairs by passing std::pair of the desired type as the template parameter when declaring std::vector.
Syntax
vector<pair<key_type, val_type>> v;
where,
- key_type: Type of the key of all the pair elements.
- val_type: Type of the value of all the pair elements.
Example
C++
// C++ Program to demonstrate how to create
// a vector of pairs
#include <bits/stdc++.h>
using namespace std;
int main() {
// Creating vector of pairs of type
// string and int
vector<pair<int,string>> v;
// Insert pairs in vector
v.push_back(make_pair(1, "Geeks"));
v.push_back(make_pair(2, "Geeksfor"));
v.push_back(make_pair(3, "GeeksforGeeks"));
for(auto i: v)
cout << i.first << " " << i.second
<< endl;
return 0;
}
Output1 Geeks
2 Geeksfor
3 GeeksforGeeks
Initialization and Insertion
We cannot initialize a vector element by directly passing key type and value type separated by a comma to any vector insertion function like vector::push_back().
v.push_back("Geeks", 1); // Incorrect
The compiler read this format as two separate arguments rather than a pair, leading to a "no matching function call" error. That is why we have to initialize the vector of pair elements by using these two methods:
Using Initializer List
In this method, we enclose the key value pair inside braces { }. The compiler then treats it as a single argument and pass it to the std::pair constructor to create a pair with given key and value.
Example
v.push_back( {"Geeks", 1} );
Using std::make_pair() Method
The std::make_pair() is a standard library function that is specifically designed only to create a std::pair from the given key and value provided as arguments. We can use this function to first create a pair and then pass it to the vector insertion function.
Example
v.push_back( std::make_pair("Geeks", 1) );
For insertion, it is recommended to use vector::emplace_back() as it avoids creating the extra copy.
Access and Assignment
We can use any of the vector access method such as access [] operator, vector::at(), vector::back() and vector::front() to access the pair at any given index. This will give us the pair that is present at this index. Then we can access the key of this pair by using .first and value using .second.
We can also assign them a new value using = assignment operator.
Example
v[2].first // Accessing key
v[2].second // Accessing value
v[2].first = 12 // Assigning key
v[2].second = "GfG" // Assigning value
Vector of Pairs with STL Algorithms
The behaviour of the STL algorithms with vector of pairs is same as that of vector of other types. But there will be some cases in which we will have to define the working of that algorithm with pairs. This is because the operation that a given algorithm performs is not defined for the std::pair by default.
For example, the std::accumulate algorithm doesn't work for vector of pairs unless we define a custom operation because the compiler doesn't know how to perform its default operation (+) addition for std::pair.
On the other hand, std::sort works find for it as its default operation < greater than is defined for std::pair.
To know which STL algorithm will work on vector of pairs, we need to know the operation of that algorithm and check if that operation is defined for std::pair or not.
More Examples of Vector of Pairs
The following examples demonstrate the use of vector of pairs in C++.
Example 1: Sorting a Vector of Pairs
C++
// C++ Program to demonstrate how to use
// std::sort on a vector of pairs
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<pair<int, string>> v;
// Inserting pairs using Initializer Lists
v.push_back({1, "Geeks"});
v.push_back({3, "GeeksforGeeks"});
v.push_back({2, "Geeksfor"});
// Sort vector
sort(v.begin(), v.end());
for (auto i : v)
cout << i.first << " " << i.second
<< endl;
return 0;
}
Output1 Geeks
2 Geeksfor
3 GeeksforGeeks
Example 2: Using std::accumulate() with Vector of Pairs
C++
// C++ Program to demonstrate how to use
// std::accumulate on a vector of pairs
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<pair<int, string>> v;
// Inserting pairs using initializer list
v.push_back({1, "Geeks"});
v.push_back({2, "Geeksfor"});
v.push_back({3, "GeeksforGeeks"});
// Initial value
pair<int, string> i(0, "");
// Defining operation for std::accumulate
// that adds first and second elements
// seperately and returns a pair
auto op = [] (pair<int, string> total,
pair<int, string>& p) {
total.first += p.first;
total.second += p.second;
return total;
};
// Using accumulate
auto sum = accumulate(v.begin(), v.end(),
i, op);
cout << sum.first << ": " << sum.second;
return 0;
}
Output6: GeeksGeeksforGeeksforGeeks
Similar Reads
How to Create a Set of Vectors in C++?
In C++, a set is a type of associative container in which duplicate elements are not allowed and a vector is a dynamic array in which duplicate elements are allowed. In this article, we will learn how to create a set of vectors in C++. For Example, Input:vector<int> vec1={1, 2, 3};vector<in
2 min read
How to Create a Set of Pairs in C++?
In C++, sets are associative containers that store unique elements. On the other hand, pairs allow the users to store two data of different or the same type into a single object. In this article, we will learn how we can create a set of pairs in C++. Example Input: p1={1, 2} p2 ={3, 4} Output: Eleme
2 min read
How to Create a Stack of Vectors in C++?
In C++, a stack of vectors can be created using the Standard Template Library (STL). The stack is a container adapter that provides a Last-In-First-Out (LIFO) type of data structure, and a vector is a dynamic array that can grow and shrink in size. In this article, we will learn how to create a stac
2 min read
How to Create a Vector of Vectors of Pairs in C++?
In C++ STL, we can nest different containers into each other at any number of levels. On such container is the Vector of Vectors of Pairs i.e. 2D vector of pairs. In this article, we will learn how to create and traverse a vector of vector of pairs in C++ STL. Vector of Vectors of Pairs in C++ The 2
3 min read
How to Create a Stack of Pairs in C++?
In C++, Stacks are a type of container adaptor with LIFO(Last In First Out) type of working, where a new element is added at one end (top) and an element is removed from that end only. A pair is a simple container that stores data in a key and value format. In this article, we will learn how to crea
2 min read
How to Create a Vector of Arrays in C++?
In C++, an array is a collection of elements of a single type while vectors are dynamic arrays as they can change their size during the insertion and deletion of elements. In this article, we will learn how to create a vector of arrays in C++. Example: Input: arr1 = {1, 2, 3}; arr2 = {4, 5, 6}; arr3
2 min read
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:v
2 min read
How to Create a Vector of Tuples in C++?
In C++, a tuple is an object that allows the users to store elements of various data types together while a vector is used to store elements of the same data types. In this article, we will learn how we can create a vector of tuples in C++. Example: Input: Tuple1 ={10,A,5.3} Tuple2= {20,B,6.5}Output
2 min read
How to Convert Map to a Vector of Pairs in C++?
In C++, map containers allow us to store the data in key-value pairs. There might be some cases where you want to convert an entire map into a vector of pairs. In this article, we will learn how to convert a map into a vector of pairs. Example Input: map<int,string>mp ={ {1,"one"}, {2,"two"},
2 min read
How to Create a Deque of Vectors in C++?
In C++, deques are sequence containers similar to queues but unlike queues, deques allow the insertion and deletion of elements from both ends efficiently. Vectors are dynamic arrays that can resize themselves during the runtime. In this article, we will learn how to create a deque of vectors in C++
2 min read