Tuples and std::tuple

Returning Multiple Values from a Function

How can I use tuples to return multiple values from a C++ function?

Vector art representing computer hardware

Tuples provide a clean way to return multiple values from a function without resorting to output parameters or complex data structures. Here's an example:

#include <string>
#include <tuple>

std::tuple<int, std::string> GetInfo(int id) {
  // Fetch player data...
  int score = 100;
  std::string name = "John";
  return {score, name};
}

int main() {
  auto [playerScore, playerName] = GetInfo(42);
  // Use playerScore and playerName...
}

The GetInfo() function returns a tuple containing the player's score and name. We can use structured bindings to conveniently unpack the returned values into separate variables.

This approach is more expressive than output parameters and avoids the overhead of creating a dedicated struct or class just for returning related values. Tuples shine for small numbers of values - for larger groups of data, a class is usually more appropriate.

This Question is from the Lesson:

Tuples and std::tuple

A guide to tuples and the std::tuple container, allowing us to store objects of different types.

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

This Question is from the Lesson:

Tuples and std::tuple

A guide to tuples and the std::tuple container, allowing us to store objects of different types.

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