...
Code Block | ||
---|---|---|
| ||
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) { cout << "Set contains: " << \*islIter << endl; } |
Non-Compliant Code Example
In this non-compliant example, the IntPtrSet
type defines a set of int pointers using the default comparison operator as the ordering rule. Unfortunately the default comparison operator will compare the pointer address values, not the values of the ints referenced by the pointers. As a result, the integers will be ordered consistently, but their order will appear to be scrambled.
Code Block | ||
---|---|---|
| ||
typedef set<int*> IntPtrSet;
IntPtrSet::const_iterator sIter;
IntPtrSet s;
int i[3] = {10, 20, 5};
s.insert(&i[2]);
s.insert(&i[1]);
s.insert(&i[0]);
cout << "Set contains ";
for (sIter = s.begin(); sIter != s.end(); ++sIter) cout << **sIter << ' ';
cout << endl;
|
TRhis code outputs:
Set contains 10 20 5
because the integers are stored in pointer order, which happens to be the order in which they are stored in the array.
Compliant Solution
Wiki Markup |
---|
To store pointers in a proper order, you should use the {{DereferenceLess}} template, as described in
\[[Meyers 01|AA. C++ References#Meyers 01]\] Item 20: |
Code Block | ||
---|---|---|
| ||
struct DereferenceLess {
template <typename PtrType>
bool operator()(PtrType pl1, PtrType pl2) const {
return *pl1 < *pl2;
}
};
|
Now if we use this template when declaring the set:
Code Block | ||
---|---|---|
| ||
typedef set<int*, DereferenceLess> IntPtrSet;
|
the rest of the program behaves as we expect:
Set contains 5 10 20
Risk Assessment
Using an invalid ordering rule can lead to erratic behavior or infinite loops.
...