C++ Using Standard Templates Today, we are going to modify our code to use the S
ID: 3907419 • Letter: C
Question
C++
Using Standard Templates
Today, we are going to modify our code to use the STL vector<> template to contain all our instances of the WITperson class we instantiate. This will allow it to grow in size without limits (except physical memory!). You will also need to instantiate an iterator for the class so that you can traverse the vector when displaying the list of persons in your database. You will need to read up on the vector<> template to implement your code. Design your test harness to allow you to insert multiple instances of your class in the vector, as well as to display them all. Use the iterator<> to accomplish this.
BONUS Points: add the ability to store your vector<> to a local file on your disk and to load it to your program when you first start the program. For now, make the file operations manual.
Explanation / Answer
#include<iostream>
#include<string>
#include<vector>
#include<fstream>
using namespace std;
//Assuming the following WITperson class
class WITperson {
private:
string name;
public:
WITperson(string a){
name = a;
}
string getName(){
return name;
}
};
class Database{
private:
vector<WITperson> list;
vector<WITperson>::iterator ptr;
public:
void add(WITperson a){
list.push_back(a);
}
void display(){
for (ptr = list.begin(); ptr < list.end(); ptr++){
cout << (*ptr).getName() << endl;
}
}
void writeToFile(){
cout << "Enter file name:";
string nm;
cin >> nm;
ofstream fout(nm.c_str());
for (ptr = list.begin(); ptr < list.end(); ptr++){
fout << (*ptr).getName() << endl;
}
fout.close();
}
};
int main(){
Database db;
cout << "Enter number of persons:";
int n;
cin >> n;
for (int i = 0; i<n; i++){
cout << "Name for " << i << "th person:";
string nm;
cin >> nm;
WITperson p(nm);
db.add(p);
}
db.display();
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.