find() and Friends
You can use the following virtual functions to test how many objects a collection contains, and whether it contains a particular object:
virtual bool contains(const RWCollectable*) const;
virtual unsigned entries() const;
virtual RWCollectable* find(const RWCollectable*) const;
virtual bool isEmpty() const;
virtual unsigned occurrencesOf(const RWCollectable*) const;
The function isEmpty() returns true if the collection contains no objects. The function entries() returns the total number of objects that the collection contains.
The function contains() returns true if the argument is equal to an item within the collection. The meaning of is equal to depends on the collection and the type of object being tested. Hashing collections use the virtual function isEqual() to test for equality, after first hashing the argument to reduce the number of possible candidates to those in one hash bucket. (Here it is important that all items which are isEqual with each other hash to the same value!). Sorted collections search for an item that compares equal to the argument; in other words, an item for which compareTo() returns zero.
The virtual function occurrencesOf() is similar to contains(), but returns the number of items that are equal to the argument.
The virtual function find() returns a pointer to an item that is equal to its argument.
The following example, which builds on the example in
Smalltalk-like Classes Example, uses
find() to find occurrences of
Mary in the collection, and
occurrencesOf() to find the number of times
Mary occurs:
#define RW_STD_TYPEDEFS 1
#include <rw/bintree.h> //1
#include <rw/collstr.h>
#include <rw/rstream.h>
using std::cout;
using std::endl;
int main(){
// Construct an empty SortedCollection
SortedCollection sc;
// Insert some RWCollectableStrings:
sc.insert(new RWCollectableString("George"));
sc.insert(new RWCollectableString("Mary"));
sc.insert(new RWCollectableString("Bill"));
sc.insert(new RWCollectableString("Throkmorton"));
sc.insert(new RWCollectableString("Mary")); //2
cout << sc.entries() << endl; //3
RWCollectableString dummy("Mary"); //4
RWCollectable* t = sc.find( &dummy ); //5
if(t){ //6
if(t->isA() == dummy.isA()) //7
cout << *(RWCollectableString*)t << endl; //8
}
else
cout << "Object not found.\n"; //9
cout << sc.occurrencesOf(&dummy) << endl; //10
sc.clearAndDestroy();
return 0;
}
Program Output:
5
Mary
2