我尝试编写一个简短的实用函数,它接受两个std::pair项和测试以确保它们的相等性,但忽略了元素的顺序。另外(这也是我遇到问题的地方),我编写了一个函数来获取这些std::pair项的容器,并测试容器中给定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
按建议添加“typename”更改代码只会导致以下错误:
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> > > >&)