C++ 用函子错误排序
不知道是否有人能帮我。下面的代码给了我这个错误: 致命错误C1903:无法从以前的错误中恢复;停止编译C++ 用函子错误排序,c++,sorting,functor,C++,Sorting,Functor,不知道是否有人能帮我。下面的代码给了我这个错误: 致命错误C1903:无法从以前的错误中恢复;停止编译 template <class T> class CompareList { public: CompareList( const long& lBlobFeature, const bool& bIsAscending ) { ... } bool operator()( T &lhs, T &rhs ) { do
template <class T>
class CompareList
{
public:
CompareList( const long& lBlobFeature, const bool& bIsAscending )
{
...
}
bool operator()( T &lhs, T &rhs )
{
double dFirstValue = lhs.GetValue( ... );
double dSecondValue = rhs.GetValue( ... );
if( m_bIsAscending ) // Sort Ascending.
{
if( dFirstValue < dSecondValue )
return true;
else
return false;
}
else // Sort Descending.
{
if( dFirstValue > dSecondValue )
return true;
else
return false;
}
}
};
CVParentList *m_pList;
m_pList = new CVChildList[ nBlobs ]; //CVChildList is a derived class of CVParentList
std::sort( m_pList, m_pList+GetBlobsNumber(), CompareList <CVChildList> ( lBlobFeature, TRUE) );
模板
类比较器
{
公众:
比较列表(常量long和lBlobFeature、常量bool和bis升序)
{
...
}
布尔运算符()(T&lhs、T&rhs)
{
双dFirstValue=lhs.GetValue(…);
双dSecondValue=rhs.GetValue(…);
if(m_bissending)//升序排序。
{
if(dFirstValuedSecondValue)
返回true;
其他的
返回false;
}
}
};
CVParentList*m_pList;
m_pList=新的CVChildList[nBlobs]//CVChildList是CVParentList的派生类
std::sort(m_pList,m_pList+GetBlobsNumber(),CompareList(lBlobFeature,TRUE));
编辑:
我真的很抱歉,实际上这是第一个错误:
错误C2664:'bool CompareList::operator()(T&,T&'):无法将参数1从'CVParentList'转换为'CVChildList&'
“致命错误C1903:无法从以前的错误中恢复;正在停止编译”
之后,我只看到最后一条错误消息。非常抱歉。可能是您需要将
const
引用传递给您的functor,因为比较不应更改要比较的对象。编译器可能需要,也可能不需要。将函子签名更改为
bool operator()(const T& lhs, const T& rhs );
您的比较器或动态列表。需要改变。您可以丢弃比较器的模板部分,只需将其声明为CVParentList比较器:
class CompareList
{
public:
CompareList(long lBlobFeature, bool isAscending);
bool operator()(const CVParentList& left, const CVParentList& right) const
{
bool ans = false;
// your comparison code goes here
return ans;
}
private:
bool m_bIsAscending;
};
并调用std::sort,就像不使用模板参数一样
std::sort( m_pList, m_pList+GetBlobsNumber(), CompareList( lBlobFeature, TRUE) );
您还可以分配列表,对其排序,然后在完成后向下投影列表标题:
CVParentList *m_pList = new CVChildList[ nBlobs ];
std::sort( (CVChildList *)m_pList, (CVChildList *)m_pList+GetBlobsNumber(), CompareList<CVChildList> ( lBlobFeature, TRUE) );
CVParentList*m_pList=new-CVChildList[nBlobs];
std::sort((CVChildList*)m_pList,(CVChildList*)m_pList+GetBlobsNumber(),CompareList(lBlobFeature,TRUE));
但是我真的建议您使用第一个选项。
bool operator()(T const&lhs,T const&rhs)
错误C1903表示编译器发现太多错误,无法继续。您可以发布整个构建日志以查看实际错误的位置吗?第一个错误,而不是最后一个,通常是有趣的错误。您是否正在尝试定义用于使用std::sort、std::map等的比较器?实际错误似乎是:错误C2664:'bool CompareList::operator()(T&,T&)“:无法将参数1从“CVParentList”转换为“CVChildList&”,我需要该模板,因为我需要实际重用函子类。因此,第二种选择奏效了。非常感谢。我太傻了,我需要做的就是把指针放下