Returning Multiple Values from a Function

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

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.

Using std::pair

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

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Using std::pair with Custom Types
Can I use std::pair with my own custom types, and if so, how?
std::pair vs Custom Struct
When should I use std::pair instead of defining my own struct or class?
Using std::pair with References
Can I store references in a std::pair, and what are the implications?
Structured Binding with std::pair
How does structured binding work with std::pair, and what are the benefits?
Template Argument Deduction with std::pair
How does template argument deduction work with std::pair, and what are the advantages?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant