Requirements for Objects in STL Containers


What is the STL? vector list

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)

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

Note 1: Some systems, like Microsoft Visual C++ 5.0 (without service packs) may require the above relational operations to be declared, if not defined. This behavior seems inconsistent with the draft ANSI/ISO C++ standard.

Note2: It may only be necessary to define the equality and "less than" operations, as STL templates may be able to synthesize the inequality and "greater than" operations from them.

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 are 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.


This document was written by Dr. Mark J. Sebern (See stl) and last updated on December 13, 1998.