Requirements for Objects Stored in C++ STL Containers

The use of STL containers places certain requirements on the objects that are stored in them. If you fail to meet these requirements, you will likely encounter compiler error messages that are very unhelpful in determining what the problems is.

Although the requirements on objects in STL containers vary by the specific container type (e.g., vector or list) and by the algorithms that you apply, you can usually avoid trouble if you abide by the following rules when designing your "container contents" classes. Assume that MyObject is the class of the object that you wish to store in an STL container. Your class should include:

Member function Example
"No argument" constructor MyObject::MyObject()
Copy constructor MyObject::MyObject(const MyObject& m)
Copy assignment operator const MyObject& MyObject::operator= (const MyObject& right)
Destructor MyObject::~MyObject()

Depending on the details of your class, the compiler-written default versions of these functions may be good enouth.

If you plan to use STL operations like find and sort, you may need the following operations:

Member function Example
Equality operator bool MyObject::operator== (const MyObject& right) const
Inequality operator bool MyObject::operator!= (const MyObject& right) const
"Less than" operator bool MyObject::operator< (const MyObject& right) const
"Greater than" operator bool MyObject::operator> (const MyObject& right) const

Although probably not necessary, you may wish to add the following operations, to complete the "relational operator" complement:

"Less than or equal" operator bool MyObject::operator<= (const MyObject& right) const
"Greater than or equal" operator bool MyObject::operator>= (const MyObject& right) const

Note that these examples are not the only way to provide the required operators. For example, you could implement the equality operator as the global function

bool operator== (const MyObject& left, const MyObject& right)

instead of the member function shown above. There are also some special templates in the <utility> library that can be used to supply missing operators, but they can be a little tricky to apply correctly. It may be easier just to get in the habit of supplying the above operations for any class you wish to store in an STL container.

Process Doc Home C++ STL
Home
Find Iterator List Container Objects Sort String Vector
Entire site content copyright © 2006 by Ensemble 74 LLC.