Adt lab/stl sets and maps

จาก Theory Wiki
ไปยังการนำทาง ไปยังการค้นหา
This is part of adt lab.

Examples

set - insert and find

#include <set>
#include <iostream>

using namespace std;

set<int> s;

main()
{
  s.insert(10);
  s.insert(20);
  s.insert(1000);
  s.insert(25);

  cout << (s.find(1) != s.end()) << endl;
  cout << (s.find(2) != s.end()) << endl;
  cout << (s.find(10) != s.end()) << endl;
  cout << (s.find(50) != s.end()) << endl;
  cout << (s.find(1000) != s.end()) << endl;

  for(set<int>::iterator i = s.begin();
      i != s.end();
      i++) {
    cout << *i << endl;
  }
}

set - using pair to prevent key clashing

#include <set>
#include <iostream>

using namespace std;

int n;
typedef pair<int,int> int_pair;

set<int_pair> s;

main()
{
  cin >> n;
  for(int i=0; i<n; i++) {
    int x;
    cin >> x;
    s.insert(make_pair(x,i));
  }
  for(set<int_pair>::iterator i = s.begin();
      i != s.end(); i++) {
    cout << i->first << endl;
  }
}

map - insertion and find

#include <map>
#include <iostream>

using namespace std;

map<int,int> m;

main()
{
  m[100] = 0;
  m[200] = 1000;
  m[1000000000] = -1;
  m[10000000] = 12345;

  cout << m[10000000] << endl;

  cout << (m.find(1000) != m.end()) << endl;

  for(map<int,int>::iterator i = m.begin();
      i != m.end(); i++) {
    cout << i->first << " -> " << i->second << endl;
  }
}