1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
|
#include <iostream>
#include <algorithm>
struct Set {
Set() = default ; // empty set
Set( const int array[] , std::size_t size, char name ) ;
~Set() { delete[] set_buffer ; }
// TODO: copy constructor, copy assignment, move constructor, move assignment
// TODO: other set operations
int* set_buffer = nullptr ; // dynamically allocated; holds the elements
// strongly consider using std::vector<> for this
std::size_t psize = 0 ;
char name = 'X' ;
};
Set::Set( const int array[] , std::size_t size, char name )
: set_buffer( new int[size]{} ), // allocate memory to hold the elements
psize(size), name(name) {
if( array != nullptr ) {
// copy the contents of array
std::uninitialized_copy( array, array+size, set_buffer ) ;
// since this is a set, we need to remove duplicate elements
std::sort( set_buffer, set_buffer+size ) ;
const auto iter = std::unique( set_buffer, set_buffer+size ) ;
psize = iter - set_buffer ; // adjust the size to the size of unique elements
}
}
std::ostream& operator<< ( std::ostream& stm, const Set& s ) {
stm << "Set '" << s.name << "' : [ " ;
for( std::size_t i = 0 ; i < s.psize ; ++i ) stm << s.set_buffer[i] << ' ' ;
return stm << "] (size:" << s.psize << ')' ;
}
int main() {
const int arr1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
const std::size_t arr1_sz = sizeof(arr1) / sizeof( arr1[0] ) ;
const int arr2[] = { 2, 4, 11, 4, 2, 4, 11, 2 };
const std::size_t arr2_sz = sizeof(arr2) / sizeof( arr2[0] ) ;
Set A( arr1, arr1_sz, 'A' );
Set B( arr2, arr2_sz, 'B' );
std::cout << A << '\n' << B << '\n' ; //I overloaded the ostream operator
}
|