Using std::pair

Using std::pair with Custom Types

Can I use std::pair with my own custom types, and if so, how?

Abstract art representing computer programming

Yes, you can use std::pair with your own custom types. std::pair is a template that accepts any two types as its template arguments. Here's an example:

#include <iostream>
#include <utility>

class Player {
 public:
  std::string name;
  int level;
};

class Guild {
 public:
  std::string name;
};

int main() {
  std::pair<Player, Guild> PlayerGuild;  

  PlayerGuild.first.name = "Anna";
  PlayerGuild.first.level = 42;
  PlayerGuild.second.name = "Adventurers";

  std::cout
    << "Player: " << PlayerGuild.first.name
    << " (Level " << PlayerGuild.first.level
    << ")\nGuild: " << PlayerGuild.second.name;
}
Player: Anna (Level 42)
Guild: Adventurers

In this example, we define two custom types: Player and Guild. We then create a std::pair named PlayerGuild that stores a Player as its first element and a Guild as its second element.

We can access and modify the members of our custom types using the first and second member variables of the pair, as shown in the example.

Remember to include the <utility> header to use std::pair in your code.

This Question is from the Lesson:

Using std::pair

Master the use of std::pair with this comprehensive guide, encompassing everything from simple pair manipulation to template-based applications

Answers to questions are automatically generated and may not have been reviewed.

This Question is from the Lesson:

Using std::pair

Master the use of std::pair with this comprehensive guide, encompassing everything from simple pair manipulation to template-based applications

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved