我正在尝试使用 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
的 transient 特性,是否不可能比较它们的整个集合?
更新:
一个建议是使用:
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> >()’
最佳答案
由于weak_ptr不支持'==',但是在这种情况下你可以使用集合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()));
这将测试等价性,而不是相等性。而且它缺乏某种……清晰度。
关于c++ - 比较两组 std::weak_ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13959743/