Gold University of Minnesota M. Skip to main content.University of Minnesota. Home page.
 
 
 

What's inside.

Ta Email

Download Compiler

Final Project

Lab Notes

Office Hours

Schedule

Syllabus

Announcements

Check Grades

 

CSci 1113 Home

 
 

Printer-friendly version

 
Vector Class Examples

3. Iterators

% cat vecT.cpp
// vector<T> example 2
#include <iostream>
using namespace std;

#include <vector>

int main()
{
   vector<int> intVec;

   intVec.push_back(7);
   intVec.push_back(2);
   intVec.push_back(8);
   intVec.push_back(3);
 
   cout << "Display using subscript notation:\n";
 
   for (int i = 0; i < intVec.size(); i++)
   {
     cout << intVec[i] << " ";
   }

   // iterator notation

   cout << "\n\nDisplay using iterator notation:\n";

   vector<int>::iterator vecIter = intVec.begin();

   while(vecIter != intVec.end() )
   {
     cout << *vecIter <<  " ";
     vecIter++;
   }

   cout << endl;

   return 0;
}
% g++ vecT.cpp
% a.out
Display using subscript notation:
7 2 8 3

Display using iterator notation:
7 2 8 3

4. Dot Product Using Iterators

% cat vecT_dot.cpp
// vector<T> example - dot product
#include <iostream>
using namespace std;
#include<cmath>

#include <vector>

double dot_product( vector<int> &, vector<int> &);

int main()
{
   vector<int> A, B;
   int NUM_EL, num;
   double dot;

   // input vector data

   cout << "Enter the number of elements in the arrays: ";
   cin >> NUM_EL;

   cout << "Enter the elements for vector A: ";
   for (int i = 0; i < NUM_EL; i++)
   {
     cin >> num;
     A.push_back( num );
   }

   cout << "Enter the elements for vector B: ";
   for (int i = 0; i < NUM_EL; i++)
   {
     cin >> num;             
     B.push_back( num );
   }

   // diplay vectors

   cout << "\n\nvector A: ";

   vector<int>::iterator vecIter = A.begin();

   while(vecIter != A.end() )
   {
     cout << *vecIter <<  " ";
     vecIter++;
   }

   cout << "\n\nvector B: ";

   vecIter = B.begin();

   while(vecIter != B.end() )
   {
     cout << *vecIter <<  " ";
     vecIter++;
   }
 
   // get the dot product

   dot = dot_product( A, B);

   cout << "\n\ndot product = " << dot << endl;

   return 0;
}

double dot_product(vector<int> &A, vector<int> &B )
{
   double dot = 0.0;
   vector<int>::iterator itA = A.begin();
   vector<int>::iterator itB = B.begin();

   while( itA != A.end() )
   {

     dot += (*itA) * (*itB) ;
 
     itA++;
     itB++;

   }
  
   return dot;
}
% g++ vecT_dot.cpp
% a.out
Enter the number of elements in the arrays: 5
Enter the elements for vector A: 2 2 2 2 2
Enter the elements for vector B: 1 2 3 4 5


vector A: 2 2 2 2 2

vector B: 1 2 3 4 5

dot product = 30

 
The University of Minnesota is an equal opportunity educator and employer.
CSci 1113: C++ Programming