Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //============================================================================
- // Name : live04-bags.cpp
- // Author :
- // Version :
- // Copyright :
- // Description : Playing with bags...
- //============================================================================
- #include <iostream>
- #include <set> // http://www.cplusplus.com/reference/set/set/
- #include <string>
- using namespace std;
- // enumeration type for actions on the bag
- enum action {add , del , qry , quit, none};
- // translation of strings into actions
- action str2action(string s){
- if (s=="add") return add;
- if (s=="quit") return quit;
- if (s=="del") return del;
- if (s=="qry") return qry;
- return none;
- }
- // a place in the bag (full declaration)
- struct item {
- double val;
- item * next;
- };
- //#define BAG_AS_ARRAY_SIZE 10
- // We will implement a bag in three ways
- struct bag {
- multiset<double> as_set; // using sets
- };
- // function to display the content of the bag
- void display_bag(bag b){
- // cout << "The bag is : " << endl;
- // Set
- // cout << " - (S) - : ";
- // std::multiset<unsigned int>::iterator it;
- // for (it = b.as_set.begin(); it != b.as_set.end(); ++it){
- // unsigned int e = *it;
- // cout << e << " " ;
- // }
- //
- // cout << endl;
- //
- return;
- }
- void insert(bag &b,double x){
- // Array
- // b.as_array[x] = true;
- // Linked list
- // we allocate a new place for the new value
- //item * i = new item;
- //i->val = x;
- //(*i).val=x;
- // we make it point to the bag
- //i->next = b.as_linked_items;
- // we set the bag now to start with the new place
- //b.as_linked_items = i;
- // Set
- b.as_set.insert(x);
- }
- void remove(bag &b, double x){
- std::multiset<double>::iterator hit(b.as_set.find(x));
- if (hit!= b.as_set.end()) b.as_set.erase(hit);
- //b.as_set.erase(x);
- }
- bool query(bag &b, double x){
- bool isPresent = 0;
- //for(int i=0; i<BAG_AS_ARRAY_SIZE; i++){
- if(b.as_set.count(x) >= 1){
- isPresent = 1;
- }
- return isPresent;
- }
- // this function deals with actions on a bag
- void update(bag &b, action a, double x){
- switch(a){
- case add:
- insert(b,x);
- break;
- case quit:
- break;
- case del:
- remove(b,x);
- break;
- case qry:
- if(query(b,x)){
- cout << "T";
- }
- else{
- cout << "F";
- }
- break;
- case none:
- break;
- default:
- break;
- }
- return;
- }
- int main(){
- bag my_bag;
- string my_act_str;
- double x;
- //initialise(my_bag);
- bool go_on = true;
- while(go_on){
- display_bag(my_bag);
- // cout << "What's next? (actions = add x , quit)" << endl;
- cin >> my_act_str;
- action act = str2action(my_act_str);
- if(act==quit){
- go_on=false;
- }
- else{
- cin >> x;
- update(my_bag,act,x);
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement