[ create a new paste ] login | about

Link: http://codepad.org/68suOr4G    [ raw code | output | fork ]

mohit_at_codepad - C++, pasted on Mar 14:
#include <iostream>
#include <set>
#include <cstdlib>
#include <ctime>
using namespace std;

class ElementHouse {
set<int> nums;
public:
ElementHouse() { srand( time(0) ); }
void InsertElement(int i) { nums.insert(i); }
void RemoveElement(int i) { nums.erase(i); }
int GetRandomElement()  {
  int sz = static_cast<int>( nums.size() );
  set<int>::iterator it = nums.begin();
  if( it != nums.end() ) {
    const int dist = rand() % sz;
    advance( it, dist );
    return *it;
  }
  // Exception handling (throw or something)
  return 0;
}
};

int main() {
  ElementHouse e;
  cout << e.GetRandomElement() << endl;
  cout << "Inserting 2" << endl;
  e.InsertElement(2);
  cout << e.GetRandomElement() << endl
       << e.GetRandomElement() << endl;
  cout << "Inserting more numbers(2, 12, 32)" << endl;
  e.InsertElement(2);
  e.InsertElement(12);
  e.InsertElement(32);
  cout << e.GetRandomElement() << endl
       << e.GetRandomElement() << endl;
  cout << "Deleting 2" << endl;
  e.RemoveElement(2);
  cout << e.GetRandomElement() << endl
       << e.GetRandomElement() << endl;

  cout << "Retrying to delete 2" << endl;
  e.RemoveElement(2);
  cout << "Returning" << endl;
  return 0;
}


Output:
1
2
3
4
5
6
7
8
9
10
11
12
0
Inserting 2
2
2
Inserting more numbers(2, 12, 32)
32
12
Deleting 2
12
12
Retrying to delete 2
Returning


Create a new paste based on this one


Comments: