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 §21 for examples.)
Non-Compliant Code Example
...
Code Block | ||
---|---|---|
| ||
typedef set<intset<int, less_equal<int > >equal<int > > IntSetLE; IntSetLE::const_iterator sleIter; IntSetLE sle; sle.insert(5); sle.insert(10); sle.insert(20); pair<IntSetLEpair<IntSetLE::const_iterator, IntSetLE::const_iterator>iterator> psle; psle = sle.equal_range(10); for (sleIter = psle.first; sleIter != psle.second; ++sleIter){ cout << "<< "Set contains: " <<" << *sleIter <<<< endl; } |
Compliant Solution
...
Code Block | ||
---|---|---|
| ||
typedef set<intset<int, less<int> >less<int> > IntSetLess; IntSetLess::const_iterator islIter; IntSetLess isl; isl.insert(5); isl.insert(10); isl.insert(20); pair<IntSetLesspair<IntSetLess::const_iterator, IntSetLess::const_iterator>iterator> pisl; pisl = isl.equal_range(10); for (islIter = pisl.first; islIter \!= pisl.second; \++islIter) { &nbsp;&nbsp;&nbsp; cout << "<< "Set contains: " <<" << \*islIter <<<< endl; } |
Risk Assessment
Using an invalid ordering rule can lead to erratic behavior or infinite loops.
...
Wiki Markup |
---|
\[[Meyers 01|AA. C++ References#Meyers 01]\] Item 21: Always have comparison functions return false for equal values.
\[[Sutter 05|AA. C++ References#Sutter 05]\] Item 83: Use a checked STL implementation.
\[[ISO/IEC 14882-2003|AA. C++ References#ISO/IEC 14882-2003]\] Section 24: Iterators Library. |
...
STL31-C. Use Valid Iterator Ranges 14. Templates and the STL (TPL) 49. Miscellaneous (MSC)