// Demonstrating STL vector constructors with a user-defined
// type and showing copying explicitly
#include <iostream>
#include <cassert>
#include <vector>
using namespace std;
class U {
public :
unsigned long id;
unsigned long generation;
static unsigned long total_copies;
U( ) : id( 0 ) , generation( 0 ) { }
U( unsigned long n) : id( n) , generation( 0 ) { }
U( const U& z) : id( z.id ) , generation( z.generation + 1 ) {
++ total_copies;
}
} ;
bool operator== ( const U& x, const U& y)
{
return x.id == y.id ;
}
bool operator! = ( const U& x, const U& y)
{
return x.id ! = y.id ;
}
unsigned long U:: total_copies = 0 ;
int main( )
{
cout << "Demonstrating STL vector constructors with a \n "
<< "user-defined type and showing copying explicitly \n " << endl;
vector< U> vector1, vector2( 3 ) ;
assert ( vector1.size ( ) == 0 ) ;
assert ( vector2.size ( ) == 3 ) ;
assert ( vector2[ 0 ] == U( ) && vector2[ 1 ] == U( ) &&
vector2[ 2 ] == U( ) ) ;
for ( int i = 0 ; i ! = 3 ; ++ i)
cout << "vector2[" << i << "].generation: "
<< vector2[ i] .generation << endl;
cout << "Total copies: " << U:: total_copies << endl;
cin .get ( ) ;
return 0 ;
}
Ly8gRGVtb25zdHJhdGluZyBTVEwgdmVjdG9yIGNvbnN0cnVjdG9ycyB3aXRoIGEgdXNlci1kZWZpbmVkCi8vIHR5cGUgYW5kIHNob3dpbmcgY29weWluZyBleHBsaWNpdGx5CiNpbmNsdWRlIDxpb3N0cmVhbT4KI2luY2x1ZGUgPGNhc3NlcnQ+CiNpbmNsdWRlIDx2ZWN0b3I+CnVzaW5nIG5hbWVzcGFjZSBzdGQ7CgpjbGFzcyBVIHsgCnB1YmxpYzogCiAgdW5zaWduZWQgbG9uZyBpZDsKICB1bnNpZ25lZCBsb25nIGdlbmVyYXRpb247CiAgc3RhdGljIHVuc2lnbmVkIGxvbmcgdG90YWxfY29waWVzOwogIFUoKSA6IGlkKDApLCBnZW5lcmF0aW9uKDApIHsgfQogIFUodW5zaWduZWQgbG9uZyBuKSA6IGlkKG4pLCBnZW5lcmF0aW9uKDAp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