This chapter introduces a very important set of ideas. A computer
keeps data in memory and we often have to store varying amounts of data
in this memory. For example if I handle grades then I will need
to store similar data about each person in a section of a course.
The generic term in C++ for this kind of storage is a
container
and this chapter introduces the two simplest containers.
An
array
contains a fixed number of similar items. They are numbered.
The program can not add a new item to the container. It can not take an
item out of the container. A container with 100 items when created has
100 items in it when we are finished with it. All we can do is
change the data in each item.
A
vector
is like an array but it can grow at one end. You can "push" new items
onto it at the back. Your can also "pop" them off the back.
Vectors are slower but more versatile than arrays.
A vector is a set of numbered cells of data inside the main
memory of the computer. For example a vector of twelve months
called month is stored and accessed like this:
Table| Number | Content | Accessed as
|
|---|
| 0 | January | month[0], or month.front()
|
| 1 | February | month[1]
|
| 2 | March | month[2]
|
| ...
|
| 11 | December | month[11] or month.back()
|
(Close Table)
- month.size() == 12
- month.empty() == false
- vector< type_name > variable_name;
- vector< type_name > variable_name ( initial_size );
- type_name::=any name of a type or class.
- variable_name::=any valid identifier.
- initial_size::=any int expression.
If the initial size is missing then the vector is initially empty.
- vector_name [ integer_expression ]
- vector_name::=an identifier declared as a vector.
- integer_expression::=any expression that returns a number that will be rounded to an int.
The program can only work if the value of the integer expression is greater than or equal
to 0, and is less than the size of the vector.
[ salvect.cpp ]
[ raisesalaries.cpp ]
[ vectors.html ]