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: 5In 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