# CS210 Lab: STL Lists Postlab Answers

### Vector Exercise:

Create a program that uses an integer vector.
Observe the following processing requirements in your program:
• Declare a integer vector.
• Declare an integer value, say "ListSize", that will be used to reference the number of elements in the vector.
• Initialize ListSize (or whatever you called it) to 0.
• Prompt the user for the value of ListSize, error checking for zero or negative values.
• Use a loop to prompt the user for the number of values specified by ListSize.
• Print out the values in the vector two times with two methods:
1. using array subscript notation
2. using a vector iterator
```// Filename: vector-ex.cpp
// Purpose: To play around with vectors.

#include <iostream.h>
#include <vector>
using namespace std;

int main()
{
vector<int> MyList;
int i;

int ListSize = 0;

cout << endl << "This program uses a vector to hold a series of numbers."
<< endl;

while (ListSize <= 0)
{
cout << endl << "Enter the number of elements in your vector: ";
cin >> ListSize;
if (ListSize <= 0)
{
cout << endl << "Size must be a positive integer.";
}
} // end while

for (i=0; i < ListSize; i++)
{
int tempint;
cout << "Please enter a number: " ;
cin >> tempint;
MyList.push_back(tempint);
}

cout << endl << "Your list now contains the following: " << endl;
cout << "Printing with the array indices" << endl;
for (i=0; i < ListSize; i++)
{
cout << MyList[i] << endl;
}

cout << "Printing with the iterator" << endl;
vector<int>::iterator p = MyList.begin();
while(p != MyList.end())
{
cout << *p << " ";
p++;
}
return 0;

} // end main
```

Back to the STLLists Lab click here

 CS Dept Home Page CS Dept Class Files CS210 Class Files

Copyright: Department of Computer Science, University of Regina.