Use vector as an array for user-defined object : object vector « vector « C++ Tutorial






#include <iostream>
#include <vector>
#include <algorithm>      
using namespace std;

class MyClass {
    int p;
public:
    MyClass() { p = 42; }
    MyClass( int q ) { p = q; }
    int getp() const { return p; }
    void changeState( int pp ) { p = pp; }
};

bool operator<( const MyClass& x1, const MyClass& x2 ) {  
       return x1.getp() < x2.getp();
}
bool operator==( const MyClass& x1, const MyClass& x2 ) { 
     return x1.getp() == x2.getp();
}

void print( vector<MyClass> );

int main()
{
     vector<MyClass> vec;                           

     MyClass x1( 2 );                               
     MyClass x2( 3 );                               
     MyClass x3( 5 );                               
     vec.push_back( x1 );
     vec.push_back( x3 );
     vec.push_back( x2 );

     print( vec );                  
     x2.changeState( 1000 );                  

     print( vec);                   

     //vector elements initialized by MyClass's no-arg      constructor:
     vector<MyClass> vec_2( 5 );          
     print( vec_2 );                
     vec_2.resize( 7 );             
     print( vec_2 );                

     //uninitialized increase in the vector capacity:
     vec_2.reserve( 10 );           
     cout << vec_2.capacity() << endl;
     print ( vec_2 );             
                                  
     cout << vec_2[ 8 ].getp() << endl;   

     vec_2[0] = MyClass(12);
     vec_2[1] = MyClass(36);
     vec_2[2] = MyClass(3);
     vec_2[3] = MyClass(56);
     vec_2[4] = MyClass(2);

     sort( vec_2.begin(), vec_2.end() );  

     print( vec_2 );

     vec_2.clear();
     print( vec_2 );
     cout << vec_2.capacity() << endl;

     return 0;
}

void print( vector<MyClass> v ) {
     cout << "\nvector size is: " << v.size() << endl;
     vector<MyClass>::iterator p = v.begin();
     while ( p != v.end() )
          cout << (*p++).getp() << "  ";
     cout << endl << endl;
}








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