【问题标题】:copying elements from std::vector to std::set based on condition but it crashes根据条件将元素从 std::vector 复制到 std::set 但它崩溃
【发布时间】:2014-03-05 20:15:15
【问题描述】:
class Information
{
public:

    const std::string comp_num() const;
    const std::string comp_address() const;

    void set_comp_address( const std::string& comp_address );
    void set_comp_num( const std::string& comp_num );

private:
    std::string comp_address_;
    std::string comp_num_;
};

class Compare
{
public:
    bool operator()(Information lf, Information rt)
    {
        return( lf.comp_num() == rt.comp_num() );
    }
};

// somwhere in function 
 std::set< Information ,Compare> test_set;
    for(  std::vector< Information >::iterator  i = old_vector.begin() ; i != old_vector.end(); ++i  )
     {
         // store all sub_cateeogroy in set
          std::cout << i->comp_num() << std::endl;// works fine 
          test_set.insert( *i ); // fails why ? Application crashes

     }

【问题讨论】:

    标签: c++ stdvector stdset


    【解决方案1】:

    std::set 要求比较器维护其元素的strict weak ordering。你的比较器没有,因为它不符合反身性和不对称性要求,可能还有其他要求。将比较器更改为以下内容将修复错误,但可能无法保留您想要的语义。

    class Compare
    {
    public:
        bool operator()(Information const& lf, Information const& rt) const
        {
            return( lf.comp_num() < rt.comp_num() );
        }
    };
    

    请注意,不需要将参数更改为Information const&amp;,但可以避免不必要的复制。

    【讨论】:

    • 我本可以度过一整夜,但无法找到错误.. 非常感谢队友
    猜你喜欢
    • 2016-03-30
    • 1970-01-01
    • 1970-01-01
    • 2018-01-11
    • 2021-06-18
    • 2011-02-23
    • 2011-05-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多