# 15 - Vector Examples Part 2

## grow.cpp

File: grow.cpp

```//Explore how vectors grow
#include <iostream>
#include <iomanip>
#include <vector>

using namespace std;

int main()
{
int limit;           //the number of elements to insert
int reallocations=0; //the number of reallocations
vector<int> v;       //my vector

//get the limit
cout << "How many items to insert? ";
cin >> limit;

//print a little table of the growth of the vector
cout << setw(9) << "Size" << setw(9) << "Capacity" << endl;
cout << setw(9) << v.size() << setw(9) << v.capacity() << endl;

//do our insertions
for(int i=0; i<limit; i++) {
//track reallocations
if(v.size() == v.capacity()) {
reallocations++;
}

//add i to the end of the vector
v.push_back(i);

cout << setw(9) << v.size() << setw(9) << v.capacity() << endl;
}

cout << "Insertions: " << v.size()
<< " Reallocations: " << reallocations << endl;
}
```

```// Buy and sell stocks
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <algorithm>

using namespace std;

//function prototypes
void sell(vector<string> &list);
void display(vector<string> &list);
void save(vector<string> &list);

int main()
{
int choice;
vector<string> stocks;

do {
//get the user's choice
cout << "          MENU" << endl
<< "    1.) Buy a Stock" << endl
<< "    2.) Sell a Stock" << endl
<< "    3.) Display Stocks" << endl
<< "    4.) Quit" << endl
<< endl
<< "    Choice? ";
cin >> choice;

} else if(choice == SELL) {
sell(stocks);
} else if(choice == DISPLAY) {
display(stocks);
} else if(choice != QUIT) {
cout << "Invalid selection, please try again." << endl;
}
} while(choice != QUIT);

//save the stock database
save(stocks);
}

{
// get the stock
string stock;
cout << "Stock> ";
cin >> stock;

// add the stock to the list
list.push_back(stock);

// sort the stocks
sort(list.begin(), list.end());
}

//sell a stock
void sell(vector<string> &list)
{
// Ask the user which stock to sell
string stock;
cout << "Sell which stock? ";
cin >> stock;

// find the stock in the list
auto itr = find(list.begin(), list.end(), stock);

// if the stock is in the list, remove it
// otherwise, report an error
if(itr != list.end()) {
list.erase(itr);
} else {
}
}

//display our holdings
void display(vector<string> &list)
{
//display the stocks in our list
for(auto itr = list.begin(); itr != list.end(); itr++) {
cout << " " << *itr;
}
cout << endl;
}

{
//open the file
ifstream file;
file.open("STOCK.LST");
if(not file) {
//return if there is no file
return;
}

while(!file.eof()) {
string stock;
if(file >> stock) {
list.push_back(stock);
}
}

//close the file
file.close();
}

//write the stocks to disk
void save(vector<string> &list)
{
//open the file
ofstream file;
file.open("STOCK.LST");
if(not file) {
//handle error
cout << "Could not open file for writing." << endl;
return;
}

//write the list to the file
for(auto itr = list.begin(); itr != list.end(); itr++) {
file << *itr << endl;
}

//close the file
file.close();
}
```