根据条件将元素从 std::vector 复制到 std::set 但它崩溃了

copying elements from std::vector to std::set based on condition but it crashes

本文关键字:std set 崩溃 复制 vector 条件 元素      更新时间:2023-10-16
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
     }

>std::set要求比较器对其元素保持严格的弱排序。您的比较器没有,因为它不符合不可反身性和不对称性要求,可能还有其他要求。将比较器更改为以下内容将修复错误,但可能无法保留所需的语义。

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

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