问题
I am trying to compare two sets of C++11 weak_ptr
using GCC 4.7.2. The code below shows the smallest possible sample reproducing the error:
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);
Trying to compile the above results in a long list of errors, of which the following is the first actual error:
/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> >()’
Due to the transient nature of weak_ptr
, is comparing an entire set of them just not possible?
Update:
One suggestion is to use:
bool result = !((set1 < set2) || (set2 < set1))
This results in:
/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:
Since weak_ptr doesn't support '==', but in this case you can use the comparison operator of the 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()));
This will test for equivalence, not equality. And it lacks a certain... clarity.
来源:https://stackoverflow.com/questions/13959743/comparing-two-sets-of-stdweak-ptr