Domanda

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

     }
È stato utile?

Soluzione

std::set requires that the comparator maintain a strict weak ordering of its elements. Your comparator doesn't because it fails the irreflexivity and asymmetry requirements, and possibly others too. Changing your comparator to the following will fix the error but it may not preserve the semantics you want.

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

Note that changing the arguments to Information const& is not required, but it avoids unnecessary copying.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top