0
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

     }
4

1 回答 1

0

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

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

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

于 2014-03-05T20:25:18.220 回答