根据条件将元素从 std::vector 复制到 std::set 但它崩溃了
copying elements from std::vector to std::set based on condition but it crashes
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&
,但它可以避免不必要的复制。
相关文章:
- 在声明中合并两个常量"std::set"(不是在运行时)
- 有没有办法对std::unordered_set、std::unrdered_map、std::set、std::map
- 将 std::set 与基于键的比较器一起使用
- 修改"std::set"中用户定义类型的值
- 如何在构造函数参数中初始化"std::set"?
- 如何使用 lower_bound/upper_bound 从 std::set 获取索引号?
- 如何在 C++ 中转发声明 std::set?
- 重构使用动态强制转换的 std::set 的比较运算符
- 为什么 std::set.erase(first, last) 会影响从中获取 (first, last) 的容器?
- std::set 是否将对象连续存储在内存中?
- 是否有一个 std::set 函数来确定不超过数字 x 的最大元素?
- 有什么理由不扩展 std::set 以添加下标运算符吗?
- 我从 std::set 得到const_iterator而不是迭代器
- 为什么 std:set(带有单个冒号)可以编译?
- 遍历 std::set 中包含的所有三重不同值?
- 插入 std::set 作为 std::map 的键
- 如何在 c++ 中使用默认值将 std::set 转换为 std::map
- 错误:'class std::unique_ptr<std::set<long unsigned int> >'没有名为 'size' 的成员
- 如何从 std::set 绘制 n 个元素的样本
- 为什么 std::set 容器使用的内存比其数据大小多得多?