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

StackOverflow https://stackoverflow.com/questions/22208230

  •  09-06-2023
  •  | 
  •  

Вопрос

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 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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top