Adt lab/stl examples

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

vector and pair

#include <vector>
#include <iostream>
using namespace std;

main()
{
  vector<pair<int,int> > a;

  for(int i=0; i<100000; i++) {
    int x = i;
    int y = i*2;
    a.push_back(make_pair(x,y));
  }
  long long s = 0;
  for(int i=0; i<100000; i++)
    s += a[i].first;
  
  cout << a.size() << " " << s << endl;
}

vector, pair, iterator

#include <vector>
#include <iostream>
using namespace std;

main()
{
  vector<pair<int,int> > a;

  for(int i=0; i<100000; i++) {
    int x = i;
    int y = i*2;
    a.push_back(make_pair(x,y));
  }
  long long s = 0;
  for(vector<pair<int,int> >::iterator i=a.begin();
      i != a.end(); i++) {
    s += i->first;
  }
  
  cout << a.size() << " " << s << endl;
}

set

#include <set>
#include <iostream>
using namespace std;

main()
{
  set<int> a;

  a.insert(10);
  a.insert(200);
  a.insert(5);
  a.insert(45);

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

set: id-request

#include <set>
#include <iostream>
using namespace std;

main()
{
  set<int> ids;
  int n;

  cin >> n;
  for(int i=0; i<n; i++) {
    int id;

    cin >> id;
    if(ids.find(id) != ids.end()) {
      cout << "Y" << endl;
    } else {
      cout << "N" << endl;
      ids.insert(id);
    }
  }
}

map: like count

#include <map>
#include <iostream>
using namespace std;

main()
{
  map<int,int> like_count;
  int n;

  cin >> n;
  for(int i=0; i<n; i++) {
    int id;

    cin >> id;
    if(like_count.find(id) == like_count.end()) {
      like_count[id] = 1;
    } else {
      like_count[id] += 1;
    }
    cout << like_count[id] << endl;
  }
}