Re: STL and the SDK
On Feb 5, 5:54 am, "Tom Widmer [VC++ MVP]" <tom_use...@hotmail.com>
wrote:
/**************Code
#include "stdafx.h"
#include <functional>
#include <algorithm>
#include <vector>
using namespace std;
class TestOb
{
public:
TestOb( int iMemInit ):m_iMem(iMemInit){}
TestOb( const TestOb & object ):m_iMem(object.m_iMem){}
TestOb& operator=( const TestOb & object ){
m_iMem = object.m_iMem;
return *this;
}
int GetInt(){
return m_iMem;
}
private:
int m_iMem;
};
class OB_COMP : public binary_function<int,TestOb,bool>
{
public:
bool operator()(int iTest, TestOb& rOb){
return iTest<rOb.GetInt();
}
bool operator()(TestOb& rOb, int iTest){
return iTest<rOb.GetInt();
}
They should both be const members (though that isn't your problem).
Additionally, you might want to define:
bool operator()(TestOb& lhs, TestOb& rhs) const;
bool operator()(int lhs, int rhs) const;
};
int _tmain(int argc, _TCHAR* argv[])
{
vector<TestOb> vObjects;
vObjects.push_back( TestOb(1) );
vObjects.push_back( TestOb(2) );
vObjects.push_back( TestOb(3) );
pair<vector<TestOb>::iterator,vector<TestOb>::iterator> prSearch =
equal_range( vObjects.begin(),vObjects.end(),2, OB_COMP() );
return 0;
}
The code is legal under the 1998 and 2003 standards I think, though the
wording in those standards is a bit odd. The following defect clarifies
what should really work:http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-defects.html#270
I think the compiler error is due to over-zealous debug checks that are
confirming that OB_COMP can compare two TestOb objects, and defines a
strict weak ordering on TestOb objects.
Tom
Well, I took the advice of Alex and made an operator < and this
brought me back to the default < operator for int and removed the need
for the OB_COMP functor. Unfortunately, this code permeates my project
and will take some time to "fix". Well at least I have a work around.
By the way, I did try several versions of const and, as Tom said, that
wasn't my problem. There was at least one other bug in the code I
posted. The bool operator()s both perform the same comparison and the
results are wrong in the release version. The functor should be:
class OB_COMP : public binary_function<int,TestOb,bool>
{
public:
bool operator()(int iTest, const TestOb& rOb){
return iTest<rOb.GetInt();
}
bool operator()(const TestOb& rOb, int iTest){
return iTest>rOb.GetInt();
}
}
The GetInt member should also be changed accordingly.
Thanks everyone for your help!