You are viewing an old version of this page. View the current version.

Compare with Current View Page History

Version 1 Next »

Providing an invalid ordering rule for an associative container or as a comparison criterion with the sorting algorithms can result in erratic behavior or infinite loops. (See [Meyers01] §21 for examples.)

Non-compliant Code Example 1

In this non-compliant example, the *IntSetLE*  type defines a set with *less_equal* specified as the ordering rule.  Less than or equal is not a valid ordering rule because it violates the requirement to provide a "strict weak ordering" over the objects compared.  In particular, this ordering rule fails to return false for equal values.  As a result, the iterator pair returned by the *equal_range()* method are inversed and the subsequent loop fails to terminate.

typedef set<int, less_equal<int > > IntSetLE;

IntSetLE::const_iterator sleIter;
IntSetLE sle;

sle.insert(5);
sle.insert(10);
sle.insert(20);

pair<IntSetLE::const_iterator, IntSetLE::const_iterator> psle;

psle = sle.equal_range(10);

for (sleIter = psle.first; sleIter \!= psle.second; \++sleIter){
&nbsp;&nbsp;&nbsp; cout << "Set contains: " << \*sleIter << endl;
}

Compliant Solution 1

Provide an ordering rule that defines a strict weak ordering.

typedef set<int, less<int> > IntSetLess;

IntSetLess::const_iterator islIter;
IntSetLess isl;

isl.insert(5);
isl.insert(10);
isl.insert(20);

pair<IntSetLess::const_iterator, IntSetLess::const_iterator> pisl;

pisl = isl.equal_range(10);

for (islIter = pisl.first; islIter \!= pisl.second; \++islIter) {
&nbsp;&nbsp;&nbsp; cout << "Set contains: " << \*islIter << endl;
}

References

* [Meyers 01|C++ References#Meyers 01] Item 21: Always have comparison functions return false for equal values.
* [Sutter 05|C++ References#Sutter 05] Item 83: Use a checked STL implementation.
* [ISO/IEC 14882-2003|C++ References#ISO/IEC 14882-2003] Section 24: Iterators Library.

  • No labels