C++/Data Structure/Set

Материал из C\C++ эксперт
Перейти к: навигация, поиск

set: insert, end, begin

#include <iostream>
#include <set>
#include <string>
using namespace std;
int main()
{
  set<string> setObject;
  setObject.insert("A");
  setObject.insert("B");
  setObject.insert("C");
  setObject.insert("D");
  set<string>::iterator p = setObject.begin();
  do {
    cout << *p << " ";
    p++;
  } while(p != setObject.end());
  cout << endl;
  p = setObject.find("C");
  if(p != setObject.end())
    cout << "Found a C\n";
  return 0;
}


Set operatrions: insert, size, begin, end

#include <iostream>
#include <string>
#include <set>
using namespace std;
int main()
{
    set<string> setObject;                                                   
    setObject.insert( "a" );                                           
    setObject.insert( "b" );                                              
    setObject.insert( "c" );                                               
    setObject.insert( "d" );                                          
    setObject.insert( "c" );                    // attempting a duplicate   
    cout << setObject.size() << endl;;                                   
    typedef set<string>::const_iterator CI;
    for (CI iter = setObject.begin();                                        
          iter != setObject.end();
          iter++)
       cout << *iter << " "; 
     setObject.erase( "b" );                                               
     cout << setObject.size() << endl;                                   
     for ( CI iter = setObject.begin();                                       
          iter != setObject.end();
          iter++ )
     cout << *iter << " "; 
     return 0;
}


Using a multiset to record responses to a polling question.

#include <iostream>
#include <set>
using namespace std;
enum response { a, 
                b, 
                c,
                d, 
                e };
int main() {
  multiset<response> question;
  // create some responses
  question.insert(response(a));
  question.insert(response(b));
  question.insert(response(c));
  question.insert(response(c));
  question.insert(response(d));
  question.insert(response(d));
  question.insert(response(d));
  question.insert(response(d));
  // display results
  cout << "a: ";
  cout << question.count(a) << endl;
  cout << "b: ";
  cout << question.count(b) << endl;
  cout << "c: ";
  cout << question.count(c) << endl;
  cout << "d: ";
  cout << question.count(d) << endl;
  return 0;
}