【问题标题】:Comparing two sets of std::weak_ptr比较两组 std::weak_ptr
【发布时间】:2012-12-19 19:31:20
【问题描述】:

我正在尝试使用 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> >()’

【问题讨论】:

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


    【解决方案1】:

    由于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()));
    

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

    【讨论】:

    • 我编辑了我的问题,并对您最初的建议发表了评论。我注意到您更新了答案,我一定会尝试一下。出于教育目的,我将保留原始编辑。
    • 另外,我认为既然我将 std::owner_less 指定为比较运算符,weak_ptr 是否实现'=='并不重要?
    • @Hans:是的,我在输入后意识到它会落入'operator
    • @Hans:问题在于容器要求指定“==”运算符使用“std::equal”和“std::set 应该使用集合指定的顺序,但这不是它的作用
    猜你喜欢
    • 2012-08-31
    • 2014-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-23
    相关资源
    最近更新 更多