Merge pull request #2317 from jwillemsen/jwi-deleteop
[ACE_TAO.git] / ACE / examples / APG / Containers / RB_Tree.cpp
blob7f29945193110f760c3cc9e003175375a13e0f9f
1 #include "ace/RB_Tree.h"
2 #include "ace/Log_Msg.h"
3 #include "ace/Synch.h"
4 #include "DataElement.h"
6 // Little helper class.
7 template<class EXT_ID, class INT_ID>
8 class Tree : public ACE_RB_Tree<EXT_ID, INT_ID,
9 ACE_Less_Than<EXT_ID>,
10 ACE_Null_Mutex>
11 {};
13 class Tree_Example
15 public:
16 // Illustrate the tree.
17 int run ();
19 private:
20 // Use the forward iterator.
21 void iterate_forward ();
23 // Use the reverse iterator.
24 void iterate_reverse ();
26 // Remove all elements from the tree.
27 int remove_all ();
29 private:
30 Tree<int, DataElement*> tree_;
33 // Listing 1 code/ch05
34 int Tree_Example::run ()
36 ACE_TRACE ("Tree_Example::run");
38 DataElement *d = 0;
39 for (int i = 0; i < 100; i++)
41 ACE_NEW_RETURN (d, DataElement (i), -1);
42 int result = tree_.bind (i, d);
43 if (result!= 0)
45 ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("%p\n"),
46 ACE_TEXT ("Bind")),
47 -1);
51 ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("Using find:\n")));
52 for (int j = 0; j < 100; j++)
54 tree_.find (j, d);
55 ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("%d:"), d->getData ()));
57 ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\n")));
59 // Use the forward iterator.
60 this->iterate_forward ();
62 // Use the reverse iterator.
63 this->iterate_reverse ();
65 // Remove all elements from the tree.
66 ACE_ASSERT (this->remove_all ()!= -1);
68 // Iterate through once again.
69 this->iterate_forward ();
71 return 0;
74 void Tree_Example::iterate_forward ()
76 ACE_TRACE ("Tree_Example::iterate_forward");
78 ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("Forward Iteration:\n")));
79 for (Tree<int, DataElement*>::iterator iter = tree_.begin ();
80 iter != tree_.end (); iter++)
82 ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("%d:"),
83 (*iter).item ()->getData ()));
85 ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\n")));
88 void Tree_Example::iterate_reverse ()
90 ACE_TRACE ("Tree_Example::iterate_reverse");
92 ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("Reverse Iteration:\n")));
93 for (Tree<int, DataElement*>::reverse_iterator iter
94 = tree_.rbegin ();
95 iter != tree_.rend (); iter++)
97 ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("%d:"),
98 (*iter).item ()->getData ()));
100 ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\n")));
103 int Tree_Example::remove_all ()
105 ACE_TRACE ("Tree_Example::remove_all");
106 ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("Removing elements\n")));
108 // Note that we can't use the iterators here as they are
109 // invalidated after deletions or insertions.
110 for (int i = 0; i < 100; i++)
112 DataElement * d = 0;
113 int result = tree_.unbind (i, d);
114 if (result != 0)
116 ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("%p\n"),
117 ACE_TEXT ("Unbind")),
118 -1);
120 ACE_ASSERT (d!= 0);
121 delete d;
124 return 0;
126 // Listing 1
128 int ACE_TMAIN (int, ACE_TCHAR *[])
130 Tree_Example te;
131 return te.run ();