CS210 Lab: STL Lists Postlab Answers


Postlab Answers:

Vector Exercise:

Create a program that uses an integer vector.
Observe the following processing requirements in your program:
// 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 Exercise click here
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.