Mega Code Archive

 
Categories / C++ Tutorial / Vector
 

Vector Creation and Element Access

#include <iostream>  #include <string>  #include <vector>  using namespace std;  class Employee  {  public:         Employee();         Employee(const string& name, const int age);         Employee(const Employee& rhs);         ~Employee();            void    SetName(const string& name);         string  GetName()      const;         void    SetAge(const int age);         int     GetAge()       const;         Employee& operator=(const Employee& rhs);   private:         string itsName;         int itsAge; }; Employee::Employee() : itsName("New Employee"), itsAge(16) {} Employee::Employee(const string& name, const int age) : itsName(name), itsAge(age) {} Employee::Employee(const Employee& rhs) : itsName(rhs.GetName()), itsAge(rhs.GetAge()) {} Employee::~Employee() {}   void Employee::SetName(const string& name) {         itsName = name; } string Employee::GetName() const {         return itsName; } void Employee::SetAge(const int age) {         itsAge = age; } int Employee::GetAge() const {         return itsAge; } Employee& Employee::operator=(const Employee& rhs) {         itsName = rhs.GetName();         itsAge = rhs.GetAge();         return *this; } ostream& operator<<(ostream& os, const Employee& rhs) {         os << rhs.GetName() << " is " << rhs.GetAge()  << " years old";         return os; } template<class T> void ShowVector(const vector<T>& v);    // display vector properties typedef vector<Employee>        SchoolClass; int main() {         Employee Harry;         Employee Sally("Sally", 15);         Employee Bill("Bill", 17);         Employee Peter("Peter", 16);         SchoolClass    EmptyClass;         cout << "EmptyClass:\n";         ShowVector(EmptyClass);         SchoolClass GrowingClass(3);         cout << "GrowingClass(3):\n";         ShowVector(GrowingClass);         GrowingClass[0] = Harry;         GrowingClass[1] = Sally;         GrowingClass[2] = Bill;         cout << "GrowingClass(3) after assigning students:\n";         ShowVector(GrowingClass);         GrowingClass.push_back(Peter);         cout << "GrowingClass() after added 4th student:\n";         ShowVector(GrowingClass);           GrowingClass[0].SetName("Harry");         GrowingClass[0].SetAge(18);         cout << "GrowingClass() after Set\n:";         ShowVector(GrowingClass);                   return 0; } template<class T> void ShowVector(const vector<T>& v) {         cout << "max_size() = " << v.max_size();         cout << "\tsize() = " << v.size();         cout << "\tcapacity() = " << v.capacity();         cout << "\t" << (v.empty()? "empty": "not empty");         cout << "\n";           for (int i = 0; i < v.size(); ++i)                 cout << v[i] << "\n";           cout << endl;  }