CHAPTER 5Tuples in C++ and their Applications

5.1 Introduction and Objectives

This chapter is devoted to a data type called tuple. A tuple (or n-tuple) is a fixed-size collection of elements. Pairs, triples and quadruples are tuples. In a programming language, a tuple is a data object containing other objects as elements or members. These elements may be of different types. In other words, tuples can hold heterogeneous data types.

We shall see some useful applications of tuples in later chapters.

5.2 An std::pair Refresher and New Extensions

In this section we pave the way for a discussion of std::tuple by reviewing the functionality in std::pair (which is a 2-tuple) and by giving examples of the new features in C++11. Much of the syntax translates directly to tuples which means that we only have to learn the syntax once and that we can later pay more attention to the design of tuples and to their applications in computational finance.

The features to be considered here are:

  1. Create pairs in two ways.
  2. Copy a pair by value and copy by reference.
  3. Accessing elements of a pair.
  4. Swapping and modifying pairs.
  5. Pair comparison.
  6. Piecewise construction and forwarding.
  7. Compile-time access to a pair's elements.
  8. Tie variables and tuple elements.
  9. Pairs and nesting.

We now discuss each of these features by describing them in general terms, by giving easy examples and by placing strategic comments in the code. Of course, the best way to learn is to program the examples yourself!

In the following ...

Get Financial Instrument Pricing Using C++, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.