append1.cpp
implements this experiment.Timer.h
, and Timer.txt
implement
the timer required by all experiments (there is no Timer.cpp
).For this experiment, the test is to append a single value to the end of an existing container:
These statements, in turn, are thetheList.push_back(1); theVector.push_back(1);
Perform the test
statements in the test
algorithms.
As we saw in the previous experiment, creating a new container takes time. This means that in this experiment, we actually have two times: creating a new container and appending the new element. Because we only wanted to measure the time for the second operation, we'll ignore the first.
Compile and execute the program on the sample range of n.
Enter the results of this experiment into the spreadsheet that you started for Experiment #1. Because we want to ignore the time that it takes to create a new container, subtract the result you got from Experiment 1 from these results for each n. These values will be the time it takes to do the append operation. Graph them.
Using the categories in Experiment #1 and your new graph, answer these questions:
Question #13.2.1: How would you categorize the time it takes to append one value to the
end of a list
of size n? Justify your answer.
Question #13.2.2: How would you categorize the time it takes to append one value to
the end of a vector
of size n? Justify your
answer.
Let's explore what's going on behind the scenes.
list
The program begins with a list
of size n
:
For simplicity, suppose thatlist<int> aList(n);
n
is 3, in which case
we have a list
like this:
The program then calls push_back()
to append a 1 to aList
:
To append 1 to theaList.push_back(1);
list
, the push_back()
operation
performs these three steps:
list
by first going through the
previous-node pointer in the head node and updating the pointers in
the header node, the last node, and the new node. Finally it
updates the size of the list
, and we end up with this:
The time for these three steps is independent of the number of
values in the list; it doesn't matter how large the list
is
to begin with; adding one more always takes the same amount of time.
vector
The program also defines a vector
of size n:
vector<int> aVector(n);
When a vector
is declared this way, the size and capacity are
the same. So if we again consider the case where n is 3, we
can visualize aVector
as follows:
The program then calls push_back()
to append a single value
to this vector
:
aVector.push_back(1);Since the size and capacity of
aVector
are the same, the
push_back()
operation follows these steps:
aVector
:
All of these steps take constant time except for Step 2. This copying takes time proportional to n because for each of the n values, we must copy the value into the new array.