Modify or Remove a Value in a Set or Multiset : multiset « set multiset « C++ Tutorial






#include <iostream>
#include <set>
#include <vector>

using namespace std;

template <class T>
void print(T& c){
   for( typename T::iterator i = c.begin(); i != c.end(); i++ ){
      std::cout << *i << endl;
   }
}

int main(){
   const int num_grades = 11;
   const int grade[num_grades] = { 2, 5, 3, 8, 9, 9, 6, 3, 5, 9, 10 };

   set<int> unique( grade, grade+num_grades );
   multiset<int> all( grade, grade+num_grades );
   print( unique );
   print( all );

   const int wrong_grade = 9;
   const int right_grade = 10;

   if( unique.erase( wrong_grade ) == 1 ){
      if( unique.insert( right_grade ).second )
         cout << "Added new, unique grade of " << right_grade << endl;
      else
         cout << "Already have unique grade of " << right_grade << endl;
   }
   else
      cout << "No unique grade of " << wrong_grade << endl;

   multiset<int>::size_type num_wrong = all.erase( wrong_grade );
   if( num_wrong > 0 ) {
      vector<int> right( num_wrong, right_grade );
      all.insert( right.begin(), right.end() );
      unique.erase( wrong_grade );
      unique.insert( right_grade );
   }
   else
      cout << "No wrong grades of " << wrong_grade << endl;

   const int drop_grade = 5;
   multiset<int>::iterator spot = all.find( drop_grade );
   if( spot != all.end() ) {
      all.erase( spot );
      if( all.count( drop_grade ) == 0 )
         unique.erase( drop_grade );
   }
   else
      cout << "Couldn't find a grade of " << drop_grade << endl;

   print( unique);
   print( all);
}








19.10.multiset
19.10.1.Add elements into an integer set and output all added elements
19.10.2.Assign elements to another multiset with ascending order
19.10.3.Initializing Associative Containers
19.10.4.Modify or Remove a Value in a Set or Multiset
19.10.5.Use std::copy to print all elements in a multiset
19.10.6.Define multiset< int, less< int > >