【问题标题】:Can't insert element into nested stl set of ints无法将元素插入到嵌套的 stl 集合中
【发布时间】:2011-04-02 07:57:05
【问题描述】:

我有一组嵌套的整数,但我无法将元素插入嵌套集。

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, 类型名称 _Alloc::rebind<_key>::other>::const_iterator, 布尔> std::set<_key _compare _alloc>::insert(const _Key&) [with _Key = int, _Compare = std::less, _Alloc = std::allocator]’ 丢弃 限定词

我无法完全解读该模板错误,感谢任何帮助。

【问题讨论】:

    标签: c++ stl set iterator


    【解决方案1】:

    集合中的元素是不可变的,您正在尝试在std::set&lt;int&gt;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);
    

    【讨论】:

    • 噢。我不知道我是否喜欢这个 glibcxx 功能。这有效地防止更改设置的内容,即使更改不会影响排序。例如。更改未比较的属性。
    • 我会说大多数有用的用例都可以更好地由关联容器(如std::map)覆盖。对我来说,这绝对比在运行时意外破坏所有内容要好。
    【解决方案2】:

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

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

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

    最外层集合的“Key”是“std::set”。比较器是“std::less>”,或者是未定义的短“operator

    我认为 std::set 没有有用的排序/比较器。你最好使用不排序元素且不需要比较器的 std::vector。

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

    【讨论】:

    • 有一个operator&lt;,参见例如here.
    • 不是运行时错误,是编译错误,这就是他的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-24
    • 2016-07-06
    • 2013-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多