Chapter 9: Vectors and Arrays

Chapter Goals

Using Vectors to Collect Data Items

Using Vectors to Collect Data Items (Syntax 9.1 Vector Variable Definition)

Syntax 9.1 : Vector Variable Definition

vector<type_name> variable_name;
vector<type_name> variable_name(initial_size);
Example:
vector<int> scores;
vector<Employee> staff(20);
Purpose: Define a new variable of vector type, and optionally supply an initial size.

Using Vectors to Collect Data Items

Using Vectors to Collect Data Items (Syntax 9.2 Vector Subscripts)

Syntax 9.2 : Vector Subscripts

vector_expression[integer_expression]
Example:
salaries[i + 1]
Purpose: Access and element in a vector.

Vector Subscripts

Vector Subscripts (salvect.cpp)

Vector Parameters and Return Values (Vector Parameters)

Vector Parameters and Return Values (matches.cpp)

Removing and Inserting Elements

Removing and Inserting Elements (erase2.cpp)

Removing and Inserting Elements (insert.cpp)


Parallel Vectors

Parallel Vectors (bestval1.cpp)

Parallel Vectors

Parallel Vectors (bestval2.cpp)


Arrays

Arrays (Syntax 9.3: Array Variable Definition)

Syntax 9.3 : Array Variable Definition

type_name variable_name[size];
Example:
int scores[20];
Purpose: Define a new variable of an array type.

Array Parameters

Array Parameters (salarray.cpp)

Character Arrays

Character Arrays (append.cpp)

Character Arrays


Two-Dimensional Arrays

Two-Dimensional Arrays (Syntax 9.4: Two-Dimensional Array Definition)

Syntax 9.4 : Two-Dimensional Array Definition

type_name variable_name[size1][size2];
Example:
double monthly_sales[NREGIONS][12];
Purpose: Define a new variable that is a two-dimensional array.

Two-Dimensional Arrays

When passing a two-dimensional array to a function, you must specify the number of columns as a constant with the parameter type.

The number of rows can be variable.

void print_table(const double table[][BALANCE_COLS], int table_rows)
{ const int WIDTH = 10;
cout << fixed << setprecision(2);
for (int i = 0; i < table_rows; i++)
{ for (int j = 0; j < BALANCES_COLS; j++)
cout << setw(WIDTH) << table[i][j];
cout << "\n";
}
}

Two-Dimensional Arrays (matrix.cpp)