Open In App

How to Create a Vector of Pairs in C++?

Last Updated : 21 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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;
}

Output
1 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;
}

Output
1 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;
}

Output
6: GeeksGeeksforGeeksforGeeks




Next Article
Practice Tags :

Similar Reads