在这个问题之后,我尝试复制粘贴在 VS2010 中找到的示例:
#include <algorithm>
#include <vector>
#include <iostream>
struct S
{
int number;
char name;
S ( int number, char name )
: number ( number ), name ( name )
{}
// only the number is relevant with this comparison
bool operator< ( const S& s ) const
{
return number < s.number;
}
};
struct Comp
{
bool operator() ( const S& s, int i )
{
return s.number < i;
}
bool operator() ( int i, const S& s )
{
return i < s.number;
}
};
int main()
{
std::vector<S> vec = { {1,'A'}, {2,'B'}, {2,'C'}, {2,'D'}, {3,'F'}, {4,'G'} }; //this syntax won't compile in VS2010, so you can leave an empty vector here
auto p = std::equal_range(vec.begin(),vec.end(),2,Comp());
for ( auto i = p.first; i != p.second; ++i )
std::cout << i->name << ' ';
}
这将在发布模式下编译正常,但在调试模式下,它将无法编译。原因是在调试模式下,实现将使用给定的谓词检查迭代器范围是否已经排序:
template<class _FwdIt,
class _Pr> inline
void _Debug_order2(_FwdIt _First, _FwdIt _Last, _Pr _Pred,
_Dbfile_t _File, _Dbline_t _Line, forward_iterator_tag)
{ // test if range is ordered by predicate, forward iterators
for (_FwdIt _Next = _First; _First != _Last && ++_Next != _Last; ++_First)
if (_DEBUG_LT_PRED(_Pred, *_Next, *_First))
_DEBUG_ERROR2("sequence not ordered", _File, _Line);
}
这最终调用:
template<class _Pr, class _Ty1, class _Ty2> inline
bool _Debug_lt_pred(_Pr _Pred,
const _Ty1& _Left, const _Ty2& _Right,
_Dbfile_t _File, _Dbline_t _Line)
{ // test if _Pred(_Left, _Right) and _Pred is strict weak ordering
if (!_Pred(_Left, _Right))
return (false);
else if (_Pred(_Right, _Left))
_DEBUG_ERROR2("invalid operator<", _File, _Line);
return (true);
}
除了在我的情况下,没有operator()
人可以同时接受左右“S”论点。那么,Visual 实现中是否存在错误?还是原始示例不应该是可移植的?我想我可以通过提供第三个 operator() 重载来使它工作,但它似乎应该在没有的情况下工作
谢谢