简体   繁体   English

C ++ std :: set无法在迭代器上使用operator +,因为编译错误

[英]C++ std::set unable to use operator + on iterator because compilation error

So I encountered a weird iterator bug ONLY on std::set : I'm unable to do a simple thing like (it + 1) on an iterator without a compilation error Try to compile this yourself : 所以我在std :: set上遇到了一个奇怪的迭代器bug:我无法在没有编译错误的迭代器上做一个像(it + 1)这样简单的事情尝试自己编译:

void setBug()
{
    std::set<int> values;

    for (auto it = values.cbegin();
         it != values.cend(); ++it) {
        if ((it + 1) != values.end())
            values.insert(*it / *(it + 1));
    }
}

error: invalid operands to binary expression ('std::_ 1:: _tree_const_iterator *, long>' and 'int') if ((it + 1) != values.end()) 错误:二进制表达式的无效操作数('std :: _ 1 :: _tree_const_iterator *,long>'和'int')if((it + 1)!= values.end())

error: invalid operands to binary expression ('std::_ 1:: _tree_const_iterator *, long>' and 'int') values.insert(*it / *(it + 1)); 错误:二进制表达式的无效操作数('std :: _ 1 :: _tree_const_iterator *,long>'和'int')values.insert(* it / *(it + 1));

compiler version : Apple LLVM version 5.0 (clang-500.2.79) (based on LLVM 3.3svn) Target: x86_64-apple-darwin13.1.0 Thread model: posix 编译器版本:Apple LLVM版本5.0(clang-500.2.79)(基于LLVM 3.3svn)目标:x86_64-apple-darwin13.1.0线程模型:posix

I found a dirty solution : (auto it2 = ++it ; --it) which works, but this is really dirty... 我找到了一个肮脏的解决方案:( auto it2 = ++ it; --it)有效,但这真的很脏......

Has somebody an explanation ? 有人解释一下吗? Is std::set broken ? std :: set坏了吗?

Thanks. 谢谢。

std::set iterators are bidirectional iterators . std::set迭代器是双向迭代器 These do not support increment via the addition operator. 这些不支持通过加法运算符的增量。 You need to increment then step by step, or use std::next or std::advance , both of which which do the same behind the scenes. 你需要逐步递增,或者使用std::nextstd::advance ,它们都在幕后做同样的事情。 This operation will be O(N) regardless. 无论如何,此操作将为O(N)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM