2011년 3월 5일 토요일

Use of structure pointer with boost::mutable_queue

I have worked on this for a few hours and finally made the whole thing work. Few article explained about either comparators with pointers or use of structure with mutable_queue, and I decided to dig the source code of STL directly. The following code is the gist of what I got from the somewhat long search:


  1. #include <iostream>
  2. #include <stdlib.h>
  3. #include <vector>
  4. #include <boost/pending/mutable_queue.hpp>
  5.  
  6. using namespace boost;
  7. using namespace std;
  8.  
  9. struct node {
  10.   int id;
  11.   int value;
  12. };
  13.  
  14. struct compare_node: public std::binary_function<struct node*, struct node*, bool>{
  15.   bool operator()(struct node *const& n1, struct node *const & n2) const {
  16.     return (n1->value < n2->value);
  17.   }
  18. };
  19.  
  20. struct node_identity_property_map : public boost::put_get_helper<std::size_t, node_identity_property_map> {
  21.   inline std::size_t operator[](struct node *const & v) const { return v->id; };
  22. };
  23.  
  24. typedef mutable_queue<struct node *, vector<struct node*>,
  25.                       compare_node, node_identity_property_map> mutable_queue_t;
  26.  
  27. #define SIZE_ID_SPACE 10
  28.  
  29. int main() {
  30.   mutable_queue_t q(SIZE_ID_SPACE, compare_node(), node_identity_property_map());
  31.  
  32.   struct node nodes[10];
  33.   cout << "putting items......" << std::endl;
  34.   for (int i = 0; i < SIZE_ID_SPACE; i++) {
  35.     nodes[i].id = i;
  36.     nodes[i].value = i;
  37.     cout << "id=value=" << i << endl;
  38.     q.push(&nodes[i]);
  39.   }
  40.  
  41.   for (int i = 0; i < SIZE_ID_SPACE; i++) {
  42.     nodes[i].value = rand();
  43.     q.update(&nodes[i]);
  44.   }
  45.  
  46.   cout << std::endl << "retrieving items......" << std::endl;
  47.   for (int i = 0; i < SIZE_ID_SPACE; i++) {
  48.     std::cout << "id: " << q.top()->id << "\t" << q.top()->value << std::endl;
  49.     q.pop();
  50.   }
  51.   return 0;
  52. }

댓글 없음: