std::cout with vectors of objects
May 30, 2009 at 6:31am UTC
Hey all,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
#include "Company.h"
#include "Casual.h"
#include "Manager.h"
#include "StaffMember.h"
#include <vector>
#include <string>
#include <iostream>
using namespace std;
Company::Company()
{
Company::name = "SkyNet" ;
vector<StaffMember*>* VSM;
StaffMember* SM1 = new Casual(001, "Jerry Seinfeld" , 250, 40);
StaffMember* SM2 = new Manager(002, "Julius Caesar" , 250000);
VSM->push_back(SM1);
VSM->push_back(SM2);
cout << "Payroll for " << Company::name << endl;
cout << "====================================" << endl;
cout << "ID Name Type Wage" << endl;
This constructor couts a few sample staffmembers. what i need to know is how do i get it to access the vector and print out.
Thanks in advance.
May 30, 2009 at 7:06am UTC
How about...You make a vector iterator, iterate through the vector, and print each object using the iterator?
May 30, 2009 at 9:18am UTC
I want to know HOW to get it to print. what do i type in order for it to access each part of the vector VSM, so to get ID, Name, Type and Wage from each vector entry.
May 30, 2009 at 1:23pm UTC
That much should segfault as-is. You don't need a pointer to your vector. Change line 13:
13 vector<StaffMember*> VSM;
now you can push_back() the StaffMember objects:
17 VSM.push_back(SM1);
18 VSM.push_back(SM2);
etc.
To print them, loop through the vector like you would any other vector.
1 2 3 4 5
for (vector::size_type n = 0; n < VSM.size(); ++n)
{
cout << setw( 6 ) << VSM[ n ]->ID << " " ;
...
}
You'll have to #include <iomanip> for that setw() manipulator.
Hope this helps.
Last edited on May 30, 2009 at 1:24pm UTC
Topic archived. No new replies allowed.