比较两组std :: weak_ptr

时间:2012-12-19 19:31:20

标签: c++ c++11 compare std stdset

我试图使用GCC 4.7.2比较两组C ++ 11 weak_ptr。下面的代码显示了再现错误的最小可能样本:

std::set<std::weak_ptr<int>, std::owner_less<std::weak_ptr<int> > > set1;
std::set<std::weak_ptr<int>, std::owner_less<std::weak_ptr<int> > > set2;

bool result = (set1 == set2);

尝试将上述结果编译成一长串错误,其中以下是第一个实际错误:

/usr/include/c++/4.7/bits/stl_algobase.h:791:6: error: no match for ‘operator==’ in ‘__first1.std::_Rb_tree_const_iterator<_Tp>::operator*<std::weak_ptr<int> >() == __first2.std::_Rb_tree_const_iterator<_Tp>::operator*<std::weak_ptr<int> >()’

由于weak_ptr的短暂性,是否比较了一整套这些不可能?

更新:

一个建议是使用:

bool result = !((set1 < set2) || (set2 < set1))

这导致:

/usr/include/c++/4.7/bits/stl_algobase.h:882:6: error: no match for ‘operator<’ in ‘__first1.std::_Rb_tree_const_iterator<_Tp>::operator*<std::weak_ptr<int> >() < __first2.std::_Rb_tree_const_iterator<_Tp>::operator*<std::weak_ptr<int> >()’

1 个答案:

答案 0 :(得分:4)

由于weak_ptr不支持'==',但在这种情况下你可以使用set try的比较运算符:

bool result = !(std::lexicographical_compare(set1.begin(), set1.end(),
                                         set2.begin(), set2.end(),
                                         set1.value_comp()) ||
                std::lexicographical_compare(set2.begin(), set2.end(),
                                         set1.begin(), set1.end(),
                                         set1.value_comp()));

这将测试等价,而不是相等。它缺乏一定的......清晰度。