Welcome the the 7th set of readings for CS201 -- Pages 58-68 of Skansholm plus the notes on the web site. This introduces a pair of powerful tools for programmers. Nearly all C++ programs have at least one array or vector in them. So far each variable we have declared has space for precisely one number. If we declare an int variable it has just enough space to be a simple counter. If we declare a double then it can hold a single measurement. With an array of 9 ints we keep track of the number of computers in the 9 CSci laboratories in Jack Brown Hall. If we have an array of of 9 doubles we can store the floor area of the 9 rooms. Arrays like this are very good when the number of items does not change. If they do change then you want one of the more modern containers of data -- vectors, deques, lists, etc. A vector of doubles could store the salaries of the faculty in the computer science department because a vector can add a new item (at the end) when some one is hired. We can also shrink the salary vector when someone retires.
Here is a summary of the reading:
type array_name [] = { item0, item1, item2, ... };
But you can not use {...} in an expression or assignment.
for( int i=0; i<size; i++)
array_name_2[i] = array_name_1[i];
#include <vector>
Quick Reference on Arrays and Vectors
Vectors are good when we have an unknown sequence of similar
items to store
and we want to access them by their sequence numbers. Arrays are best
when we know the maximum possible number of items -- and we want a program
to run faster.
Vectors are held in a special library and can be used in a file that has
#include <vector>at its beginning.
| Declare v | vector<type> v(initial_size); |
| Copy v2 into v1 | v1 = v2; |
| Get data from v | v.empty(), v.size(), v.front(), v.back(), v[number], v1==v2 |
| Change ith item in v | v[i]=new_value; |
| Add/Remove items | v.push_back(item), v.pop_back() |
Arrays are part of the C language and so part of C++. You do not "#include" anything because the compilers knows about them already. There are no special operations/function that work on arrays.
| Declare a to have n | type a[n]; |
| Copy a1 into a2 | Write a for loop! |
| Get data from a | a[number] |
| Change ith item in a | a[i]=new_value; |
| Add/Remove items | Impossible. |
Details
Suppose that T is any type or class - say int, float, double, or
the name of a class, then
vector<T> v;declares a new and empty vector called v. Given object v declared like the above you can do the following things with it:
v.empty()
v.size()
v.push_back(t)
v.pop_back()
v.first()
v.last()
v[i]
Assign a copy of v1 to v:
v = v1
Example
Suppose that we want to input an unknown number of numbers and then print them
out forwards and then backwards, using a vector. We will push ints onto the back of a vector
called v. We will then print each item in v in turn. Finally we will print the
vector backwards.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> v;
int number;
// 1. Input v;
cout <<"Input some numbers and then end the input\n";
while(cin>>number){
v.push_back(number);
}//while(more)
// 2. Print v
for(int i=0; i<v.size(); ++i)
cout << v[i] << " ";
cout << endl;
cout << "----------------"<<endl;
// 3. Print backwards
for(int i=v.size()-1; i>=0; --i)
cout << v[i] << " ";
cout << endl;
}//main
More About Arrays
A vector is a simple dynamic sequential "container".
The oldest example
of a container in C++ is the array. It is a static sequential
container. In C you
had arrays and you would
write code like this:
const int MAX = 10;
float a[MAX];
...
cout << "Input "<< MAX << "numbers."
for(int i=0; i<MAX; ++i)
cin>> a[i];
...
for(int i=0; i<MAX; ++i)
cout << a[i] << " ";
...
for(int i=MAX-1; i>=0; --i)
cout << a[i];
...Arrays are like vectors except that:
You must be sure that all indices or subscripts of a vector v stay between 0 and v.size()-1 inclusive.
Trying to change the size of an array does not work.
You must be sure that all indices or subscripts of a array a stay between 0 and MAXIMUM-1 inclusive if the array is declare with size MAXIMUM.
If a program compiles, loads, crashes, and there is a subscript operator ([...]) then check to see if the subscripted item has been put into the container before the subscripted element is accessed. A very common error is to declare a vector with no length and to use [...] as if it created new elements. It doesn't. Use 'push_back(..)' to add new elements to a vector.
If you are unable to show that a subscript is in range then use a condition like the following to guard thing[i] from errors:
0<= i && i < thing.size()
If a program compiles, loads and crashes and it has a pop_back, function than make sure that there is an item to be "popped"! In code you can use the empty function to guard statements that contain "pop" from blowing up.
You can have vectors of vectors:
vector < vector <int> > matrix;but you must put at least one space between the two ">" symbols. The following is wrong:
vector < vector <int>> matrix;
2 and 3 dimensional arrays
C++ doesn't have 2 or 3 dimensional arrays -- a[r,c], b[i,j,k] -- even
tho' this code compiles! You have to declare and use arrays or arrays
to get 2 or 3 dimensions:
double matrix[ROW][COLUMN];
// print matrix
for(int row=0; row<ROW; row++)
{
for(int column=0; column<COLUMN; column++)
cout << matrix[row][column] << " ";
cout << endl;
}
. . . . . . . . . ( end of section Errors) <<Contents | End>>
Tracing is used as the first step to understanding a program.
It is also a useful training technique and diagnostic test of how well you understand something.
We traced a piece of code like this in class:
int t = 0;
for (int i=0; i < 5; i++)
{
t = t + i;
cout << t << endl;
}
| Statement\Variables | t | i | cout |
|---|---|---|---|
| t=0 | 0 | ? | ? |
| i=0 | 0 | 0 | ? |
| i<5 | |||
| t=t+i | 0 | 0 | ? |
| cout | 0 | 0 | 0 |
| i++ | 0 | 1 | |
| i<5 | |||
| t=... | 1 | 1 | |
| cout... | 1 | 1 | 1 |
| i++ | 1 | 2 | |
| i<5 | |||
| t... | 3 | 2 | |
| cout | 3 | 2 | 3 |
| ... | |||
| cout | 10 | 4 | 10 |
| i++ | 10 | 5 | |
| i>=5 |
if statements and iomanip
You don't need any libraries to use if.
Difference between float and double
Both store real numbers. Float uses less space and may
run faster. Doubles have more significant figures.
How are arrays and vectors helpful
Doing without them is painful in the extreme -- believe me!
Why can't we use vectors instead of arrays
Their are only two reasons for using arrays: (1) they are efficient
(faster, less wasted space) and (2) you have to fit with software
that uses an array.
Can vectors be used in place of arrays
Yes!
In this class -- use vectors whenever you have the option.
When do I use vectors
Always!
When do I use deques
In CS202 and/or CS330.
What functions are part of the vector library
Check out the full documentation in
How to stop the user inputting bad data -- letter in a number
Todays lab shows the cin.fail() condition in action. It may help.
Can you explain vectors more
Check out the notes above.
Or come and ask questions in my office hours.
What are vectors actually used for
Storing a collection of data items in memory
and to allow us to reorganize the data.
What kind of program uses arrays vs vectors
Old programs used arrays -- no choice. Modern programs tend
to use vectors. Exception to speed up code.
How does the size of an array relate to the last subscript
If the last subscript is 5 then the size will be 6 elements.
Can you give a clear definition of an array
A fixed number of items of the same type numbered from 0 upward.
What happens if we put a string into an array of ints
C++ will convert the string into an address and store that!
What functions are part of the vector library
Check out the documentation in
[ ../samples/stl.html#Vectors ]
[ ../c++std/cd2/lib-containers.html ]
(from the draft standard...)