我试图编写一个简短的实用函子,它接受两个 std::pair 项目并测试它们的相等性,但忽略元素的顺序。此外(这是我遇到麻烦的地方)我编写了一个函数来获取这些 std::pair 项目的容器并测试容器中给定对参数的成员资格。
/* A quick functor way to check the identity of the two items of a pair to see if each pair contains the same items regardless of order */
template <class T>
class EqualPairs : public std::binary_function<T,T,bool> {
T arg2;
public:
explicit EqualPairs (const T& x) : arg2(x) { }
bool operator() (const T& arg1) {
bool same = false;
if (arg1 == arg2 || (arg1.first == arg2.second && arg1.second == arg2.first))
same = true;
return same;
}
};
/* checks to see if the give pair p is a member of the list of pairs l. The pairs are compared disregarding the order of the pair elements (i.e. (4,2) == (2,4)) */
template <class P>
bool PairListMember (const P& p, const std::vector<P>& l)
{
std::vector<P>::iterator it;
it = find_if (l.begin(), l.end(), EqualPairs<P>(p));
bool member_of_list = (it != l.end()) ? true : false;
return member_of_list;
}
我想不出一种允许通用容器选择的干净方法,所以我现在将 std::vector 硬编码为容器类型。对使容器类型通用的帮助也将不胜感激,但现在我只想让上面的内容编译和工作。我得到的错误是:
In function ‘bool PairListMember(const P&, const std::vector<P, std::allocator<_CharT> >&)’:
error: expected `;' before ‘it’
error: ‘it’ was not declared in this scope
In function ‘bool PairListMember(const P&, const std::vector<P, std::allocator<_CharT> >&) [with P = std::pair<int, int>]’:
error: dependent-name ‘std::vector<P,std::allocator<_CharT> >::iterator’ is parsed as a non-type, but instantiation yields a type
note: say ‘typename std::vector<P,std::allocator<_CharT> >::iterator’ if a type is meant
按照建议通过添加“类型名称”来更改代码只会导致以下错误:
error: no match for ‘operator=’ in ‘it = std::find_if [with _InputIterator = __gnu_cxx::__normal_iterator<const std::pair<int, int>*, std::vector<std::pair<int, int>, std::allocator<std::pair<int, int> > > >, _Predicate = EqualPairs<std::pair<int, int> >](((const std::vector<std::pair<int, int>, std::allocator<std::pair<int, int> > >*)l)->std::vector<_Tp, _Alloc>::begin [with _Tp = std::pair<int, int>, _Alloc = std::allocator<std::pair<int, int> >](), ((const std::vector<std::pair<int, int>, std::allocator<std::pair<int, int> > >*)l)->std::vector<_Tp, _Alloc>::end [with _Tp = std::pair<int, int>, _Alloc = std::allocator<std::pair<int, int> >](), EqualPairs<std::pair<int, int> >(((const std::pair<int, int>&)((const std::pair<int, int>*)p))))’
/usr/include/c++/4.2/bits/stl_iterator.h:637: note: candidates are: __gnu_cxx::__normal_iterator<std::pair<int, int>*, std::vector<std::pair<int, int>, std::allocator<std::pair<int, int> > > >& __gnu_cxx::__normal_iterator<std::pair<int, int>*, std::vector<std::pair<int, int>, std::allocator<std::pair<int, int> > > >::operator=(const __gnu_cxx::__normal_iterator<std::pair<int, int>*, std::vector<std::pair<int, int>, std::allocator<std::pair<int, int> > > >&)