Vector Class Examples
1. Initialization, capacity(), size(), push_back()
% cat vect.cpp
// vector<T> example
#include <iostream>
using namespace std;
#include <vector>
int main()
{
int i;
vector<int> item(10, 7);
cout << "capacity is " << item.capacity()
<< "\nsize is " <<
item.size() << endl;
item.push_back(9);
cout << "capacity is " << item.capacity()
<< "\nsize is " <<
item.size() << endl;
cout << "Elements of vector: \n";
for(i = 0; i < item.size(); i ++)
cout << item[i] << endl;
cout << "back = " << item.back() << endl;
}
% g++ vect.cpp
% a.out
capacity is 10
size is 10
capacity is 20
size is 11
Elements of vector:
7
7
7
7
7
7
7
7
7
7
9
back = 9
2. Dot product of two vectors
% cat vect_dot_index.cpp
// vector<T> example - dot product
// Use vector index operation
#include <iostream>
using namespace std;
#include<cmath>
#include <vector>
double dot_product( vector<double> &, vector<double> &);
int main()
{
vector<double> 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: ";
for(int i = 0; i < NUM_EL; i++ )
{
cout << A[i] << " ";
}
cout << "\n\nvector B: ";
for(int i = 0; i < NUM_EL; i++ )
{
cout << B[i] << " ";
}
// get the dot product
dot = dot_product( A, B);
cout << "\n\ndot product = " << dot << endl;
return 0;
}
double dot_product(vector<double>& A, vector<double>&
B )
{
double dot = 0.0;
int NUM_EL;
NUM_EL = A.size();
for(int i=0; i < NUM_EL; i++ )
{
dot += A[i]*B[i];
}
return dot;
}
% g++ vect_dot_index.cpp
% a.out
Enter the number of elements in the arrays: 4
Enter the elements for vector A: 1 2 3 4
Enter the elements for vector B: 2 2 3 3
vector A: 1 2 3 4
vector B: 2 2 3 3
dot product = 27
|