Skip to main content

Section 14.6 Typedefs

C++ data types can sometimes become a bit much to efficiently read or type:
  • vector< vector<int> > - a two dimensional vector of integers
  • vector< vector<int> >::iterator - an iterator over a two dimensional vector of integers
  • map< char, vector<string> > - a map of characters to vectors of strings
To make it easier to read and write, we can use a typedef. A typedef is a way to give a new name to an existing type. The new name can be shorter or more descriptive. The basic syntax is:
typedef EXISTING_TYPE NEW_NAME;
For example, we could give the name Matrix to the type vector< vector<int> > like this:
typedef vector< vector<int> > Matrix;

Note 14.6.1.

It is a common convention to capitalize new data types or names for data types. That way, when you see Matrix you can guess it is the name of a type of data, not the name of a piece of data.
A typedef like this would normally go outside of any particular function near the top of a code file so that it is available everywhere in that file. If we are building a program with multiple files and want to use the same typedef across many of them, we would write it in a .h file or module that gets included in all the places it is needed.
Once we have made the typedef we can use Matrix instead of vector< vector<int> > in our code. So the function that takes a two dimensional vector of integers could be written as:
void foo(const Matrix& m);
The new name and the old are interchangeable - they are just different names the same type of thing. So it is perfectly legal to mix and match the names when working with items of that type:
Listing 14.6.1.
// IntTable is a type alias for vector<vector<int>>
typedef vector<vector<int>> IntTable;
// Make a 2D vector
vector<vector<int>> table = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
// Use type alias to make a reference
IntTable& table2 = table;
It should be noted that overusing typedef can make code less readable. Especially if it is used to assign new names to simple types. Don’t use typedef to make Decimal mean double!
You have attempted of activities on this page.