Store a class object in a vector. : object vector « vector « C++ Tutorial






#include <iostream>
#include <vector>
#include <cstdlib>
using namespace std;
   
class DailyTemp {
  int temp;
public:
  DailyTemp() { temp = 0; }
  DailyTemp(int x) { temp = x; }
   
  DailyTemp &operator=(int x) {
    temp = x; return *this;
  }
   
  double get_temp() { return temp; }
};
   
bool operator<(DailyTemp a, DailyTemp b)
{
  return a.get_temp() < b.get_temp();
}
   
bool operator==(DailyTemp a, DailyTemp b)
{
  return a.get_temp() == b.get_temp();
}
   
int main()
{
  vector<DailyTemp> v;
  unsigned int i;
   
  for(i=0; i<7; i++)
    v.push_back(DailyTemp(60 + rand()%30));
   
  cout << "Fahrenheit temperatures:\n";
  for(i=0; i<v.size(); i++)
    cout << v[i].get_temp() << " ";
   
  cout << endl;
   
  // convert from Fahrenheit to Centigrade
  for(i=0; i<v.size(); i++)
    v[i] = (int)(v[i].get_temp()-32) * 5/9 ;
   
  cout << "Centigrade temperatures:\n";
  for(i=0; i<v.size(); i++)
    cout << v[i].get_temp() << " ";
   
  return 0;
}








16.31.object vector
16.31.1.Store a class object in a vector.
16.31.2.vector with 10 objects
16.31.3.Object vector
16.31.4.Call member function for each element in vector
16.31.5.Call the virtual function from classes stored in a vector
16.31.6.Use vector to store the calsses in a hiearchy
16.31.7.Use vector as an array for user-defined object