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.
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:
- Create pairs in two ways.
- Copy a pair by value and copy by reference.
- Accessing elements of a pair.
- Swapping and modifying pairs.
- Pair comparison.
- Piecewise construction and forwarding.
- Compile-time access to a pair's elements.
- Tie variables and tuple elements.
- 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 ...