Skip to main content

Section 14.7 Functions for Multidimensional Vectors

When writing functions with multidimensional vectors, we should follow the same guideline as writing functions for normal vectors. Primarily, we should use pass by reference to avoid making needless copies of our data. If we don’t intend on modifying the data, we should use pass by const reference.
If we are writing multiple functions that all work with the same multidimensional data type, a typedef make make our code easier to read. For example, say we are working with two dimensional vectors of integers and want to write a function doubleAll that takes a table of data as a parameter, and returns a new table where all the values are doubled. We can either use the prototype on line 1, or we can do the typedef on line 3 and then write the prototype shown on line 4.
vector<vector<int>> doubleAll(const vector<vector<int>>& table);

typedef vector<vector<int>> IntTable;
IntTable doubleAll(const IntTable& table);
In this sample, we use two functions to work with a multidimensional collection of numbers:
Listing 14.7.1.
Note that these functions calculate the colCount for each row. Previous samples calculated one colCount based on the size of the first row. Calculating each row’s length independently means these functions will work correctly on β€œjagged” structures. Rectangular data has the same number of columns in every row. In non-rectangular or jagged data, each row can have a different length.
// Jagged data
1 2
3 4 5
6

// Rectangular data
1 2 3
4 5 6
You have attempted of activities on this page.