首页 文章

无法将元素插入到嵌套的stl集合中

提问于
浏览
2

我有一组嵌套的int但我不能将元素插入到嵌套集中 .

std::set<std::set<int> > centre_as_set = bitset_to_set(centre->second->bit_partitions);
std::set<std::set<int> >::iterator set_itr;
for ( set_itr = centre_as_set.begin(); set_itr != centre_as_set.end(); ++set_itr ) {
    set_itr->insert(4);
    std::set<int>::iterator node_itr;
    for ( node_itr = set_itr->begin(); node_itr != set_itr->end(); ++node_itr ) {
            std::cout << *node_itr;
        }
    }
}

错误是

Partition_standalone.cpp:612:错误:将'const std :: set,std :: allocator>'作为'std :: pair,_Compare,typename _Alloc :: rebind <_Key> :: other>的'this'参数传递: :const_iterator,bool> std :: set <_Key,_Compare,_Alloc> :: insert(const _Key&)[with _Key = int,_Compare = std :: less,_Alloc = std :: allocator]'丢弃限定符

我无法解释该模板错误,任何帮助表示赞赏 .

2 回答

  • 5

    集合中的元素不可变,并且您试图在 std::set<int>const 实例上使用非const成员函数 insert() . 如果您在 stl_set.h 中按照 iterator 符号进行声明,则会有以下好评:

    // _GLIBCXX_RESOLVE_LIB_DEFECTS
    // DR 103. set::iterator is required to be modifiable,
    // but this allows modification of keys.
    typedef typename _Rep_type::const_iterator iterator;
    

    C 98和C 03允许修改,但这是一个缺陷,已经在非古老的GCC版本和VC10中得到修复 . 上述缺陷报告可以在here找到,并将纳入下一个标准 .

    使用例如类似于以下内容而不是添加值 4

    // Readability:
    typedef std::set<int> IntSet;
    typedef std::set<IntSet> IntSetSet;
    
    // Helper:
    IntSetSet add_value_to_sets(const IntSetSet& in, int i) {
        IntSetSet ss;
        IntSetSet::iterator set_itr;
        for ( set_itr = in.begin(); set_itr != in.end(); ++set_itr ) {
            IntSet s = *set_itr;
            s.insert(4);
            ss.insert(s);
        }
        return ss;
    }
    
    // ...
    IntSetSet centre_as_set = 
        add_value_to_sets(bitset_to_set(centre->second->bit_partitions), 4);
    
  • 0

    编辑:根据georg的评论,这个答案是错误的 .

    我这里没有编译器,但std :: set的完整声明是:

    template < class Key, class Compare = less<Key>,
               class Allocator = allocator<Key> > class set;
    

    最外层集的“密钥”是“std :: set” . 比较器是“std :: less>”或短“operator <(set,set)”,它是未定义的 . 编译器仅在比较器的第一次使用/实例化时警告此情况 .

    我不认为std :: set有一个有用的排序/比较器 . 你最好使用std :: vector,它不对元素进行排序,也不需要比较器 .

    哦,如果这会影响排序,则不允许更改(在运行时)设置键 . 但那将是运行时错误,而不是编译错误 .

相关问题