So, your question is about printing all the elements of a vector? As an example:
Code:
#include <string>
#include <iterator>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct person
{
string name;
int age;
person(string n,int a) : name(n), age(a) {}
};
// Overloaded stream insertion operator
ostream& operator<<(ostream& os,const person& p)
{
return os << p.name << " is " << p.age << " years old.";
}
int main()
{
vector<person> people;
vector<person>::size_type loop;
vector<person>::iterator it;
// Insert person objects onto vector.
people.push_back(person("Homer",42));
people.push_back(person("Lisa",10));
people.push_back(person("Bart",12));
// Print method #1 use manual loop and manual printing w/ indexing
for( loop = 0; loop < people.size(); ++loop )
{
cout << people[loop].name << " is "
<< people[loop].age << " years old."
<< endl;
}
// Print method #2 use manual loop and manual printing but w/ iterators
for( it = people.begin(); it != people.end(); ++it )
{
cout << it->name << " is "
<< it->age << " years old."
<< endl;
}
// Print method #3 use manual loop and indexing but with operator<<
for( loop = 0; loop < people.size(); ++loop )
{
cout << people[loop] << endl;
}
// Print method #4 use copy STL function... (uses operator<<)
copy(people.begin(),people.end(),ostream_iterator<person>(cout,"\n"));
cout.flush();
return 0;
}
All of those methods should output the same thing, so you should have 4 copies of the following:
Code:
Homer is 42 years old.
Lisa is 10 years old.
Bart is 12 years old.
There are other ways as well, you could use a manual loop with iterators that uses the overloaded operator<< for example.