#include #include /****************************************************** * A container is an object whose purpose is to store * and organize a collection of values. * * The C++ Standard Library provides several container * classes. One of these is std::set. * * A std::set stores a collection of unique values in * sorted order. If you insert the same value more than * once, only one copy is stored. * * For example, * * std::set data{}; * * creates an empty set that stores integers. * * We interact with a set using member functions: * * data.insert( value ); // Insert a value * data.size(); // Number of values * data.count( value ); // 1 if present, 0 otherwise * data.erase( value ); // Remove a value * data.begin(); // Iterator to first value * data.end(); // Iterator past last value * * Notice the syntax: * * object.member_function( arguments ) * * The member functions control how we access and * modify the values stored in the container. ******************************************************/ // Function declaration int main(); // Function definition int main() { // Create an empty set that stores integers. std::set data{}; // 100 random integers int random[100]{ 26, 61, 15, 2, 86, 1, 32, 37, 91, 73, 97, 5, 9, 20, 56, 70, 89, 18, 99, 24, 64, 79, 77, 37, 50, 76, 65, 49, 7, 94, 4, 1, 86, 8, 60, 19, 99, 63, 38, 94, 76, 49, 62, 37, 85, 28, 4, 21, 8, 39, 61, 6, 79, 6, 1, 91, 84, 44, 39, 39, 68, 28, 86, 92, 86, 3, 56, 64, 14, 42, 32, 59, 38, 50, 28, 92, 52, 84, 64, 90, 82, 44, 78, 39, 24, 0, 94, 46, 49, 75, 32, 19, 3, 46, 71, 0, 59, 29, 47, 16 }; // insert(...) adds a value to the set. Duplicate // values are ignored. for ( std::size_t k{0}; k < 100; ++k ) { data.insert( random[k] ); } // size() returns the number of values in the set. std::cout << "The size of 'data' is " << data.size() << std::endl; int delete_count{0}; for ( int k{3}; k < 100; k += 13 ) { // count(...) returns 1 if the value is in the set // and 0 otherwise. std::cout << "Erasing " << k << " which has count " << data.count( k ) << std::endl; // erase(...) removes the value and returns the number // of entries removed: either 0 or 1 for a set. delete_count += data.erase( k ); } std::cout << delete_count << " entries were deleted" << std::endl; std::cout << "The size of 'data' is now " << data.size() << std::endl; // begin() returns an iterator to the first value and // end() represents the position just past the last. // // The values appear in sorted order. for ( std::set::iterator itr{ data.begin() }; itr != data.end(); ++itr ) { std::cout << *itr << " "; } std::cout << std::endl; return 0; }