简体   繁体   English

无效的迭代器比较

[英]invalid iterator comparison

I have written this piece of code to find duplicate items in the string vector "elements". 我已经编写了这段代码,以在字符串向量“ elements”中查找重复项。 A storage for the unique items is kept, and if an item is found in the unique storage it means it's a duplicate: 保留了唯一项的存储,如果在唯一存储中找到了某项,则表示它是重复项:

    vector<string> elements;
    // "elements" is populated ....
    //  ...

    // Find duplicates:
    vector<string> uniqueElements;

    for (int i = 0; i < elements.size(); ++i)
    {
        string name = elements[i];
        vector<string>::iterator it = find(uniqueElements.begin(), uniqueElements.end(), name);

        if(it != uniqueElements.end()) // ERROR
        {
            cerr << "Duplicate element " << name << endl;
            return false;
        }
        uniqueElements.push_back(name);
    }

After the 2nd item in the "elements" vector, when the uniqueElements container is reallocated I am getting a 在“元素”向量中的第二项之后,重新分配uniqueElements容器后,我得到了

    vector iterators incompatible

error message. 错误信息。 Why does this happen, since I am getting new iterators at the beginning of each loop. 为什么会发生这种情况,因为在每个循环的开始我都会得到新的迭代器。

Thanks in advance. 提前致谢。

Thank you for the responses,turns out it was something different. 谢谢您的答复,事实却有所不同。 In my original code, the error I was printing was 在我的原始代码中,我打印的错误是

 cerr << "Duplicate element " << name << " at position " << it - elements.begin() <<  endl;

I omitted the exact print content thinking that it was irrelevant, but of course the error was that I was using the iterator on a different vector. 我忽略了与打印内容无关的确切打印内容,但是当然错误是我在不同的向量上使用了迭代器。 Sorry for the trouble. 抱歉,添麻烦了。

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

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