Using std::pair

Returning Multiple Values from a Function

How can I use std::pair to return multiple values from a function?

Abstract art representing computer programming

std::pair provides a convenient way to return multiple values from a function. You can use it as the return type of your function, and then return a pair object containing the desired values. Here's an example:

#include <iostream>
#include <utility>

std::pair<int, bool> divide(int a, int b) {
  if (b == 0) {
    return {0, false};  
  } else {
    return {a / b, true};  
  }
}

int main() {
  auto [result, success] = divide(10, 2);  
  if (success) {
    std::cout << "Result: " << result;
  } else {
    std::cout << "Division by zero!";
  }
}
Result: 5

In this example, the divide function takes two integers a and b as parameters and returns a std::pair<int, bool>. The first element of the pair is the division result, and the second element is a boolean indicating whether the division was successful (i.e., b was not zero).

Inside the function, we check if b is zero. If it is, we return a pair with 0 as the result and false for success. Otherwise, we return a pair with the division result and true for success.

In the main function, we call divide(10, 2) and use structured binding to unpack the returned pair into two variables: result and success. We then check the success value and print the result if the division was successful, or print an error message otherwise.

By using std::pair, we can easily return multiple related values from a function in a single return statement.

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:

  • 125 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