Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Edited by NavBot (jp)

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
bgColor#FFcccc
typedef set<intset&lt;int, less_equal<int > >equal&lt;int &gt; &gt; IntSetLE;

IntSetLE::const_iterator sleIter;
IntSetLE sle;

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

pair<IntSetLEpair&lt;IntSetLE::const_iterator, IntSetLE::const_iterator>iterator&gt; psle;

psle = sle.equal_range(10);

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

Compliant Solution

...

Code Block
bgColor#ccccff
typedef set<intset&lt;int, less<int> >less&lt;int&gt; &gt; IntSetLess;

IntSetLess::const_iterator islIter;
IntSetLess isl;

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

pair<IntSetLesspair&lt;IntSetLess::const_iterator, IntSetLess::const_iterator>iterator&gt; pisl;

pisl = isl.equal_range(10);

for (islIter = pisl.first; islIter \!= pisl.second; \++islIter) {
&amp;nbsp;&amp;nbsp;&amp;nbsp; cout << "&lt;&lt; &quot;Set contains: " <<&quot; &lt;&lt; \*islIter <<&lt;&lt; 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)