Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C++
  • Standard Template Library
  • STL Vector
  • STL List
  • STL Set
  • STL Map
  • STL Stack
  • STL Queue
  • STL Priority Queue
  • STL Interview Questions
  • STL Cheatsheet
  • C++ Templates
  • C++ Functors
  • C++ Iterators
Open In App
Next Article:
How to Create a Stack of Vectors in C++?
Next article icon

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++.

Table of Content

  • What is Vector of Pairs in C++?
  • Example
  • Initialization and Insertion
  • Access and Assignment
  • Vector of Pairs with STL Algorithms
  • More Examples of Vector of Pairs

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
How to Create a Stack of Vectors in C++?
author
abulhax
Improve
Article Tags :
  • C++ Programs
  • C++
  • STL
  • cpp-vector
  • cpp-pair
  • CPP Examples
Practice Tags :
  • CPP
  • STL

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 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 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 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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences