繁体   English   中英

仅在Visual Studio中出现C ++向量迭代器不兼容错误

[英]C++ `vector iterators incompatible` error only in Visual Studio

我有一个类,通过这些单词的向量和该向量上的迭代器来表示由空格分隔的单词的字符串。

class WordCrawler{
public:
    WordCrawler(std::string, bool reversed=false);
    WordCrawler& operator--();
    std::string operator*  () const;

    bool atBeginning() const;
private:
    std::vector<std::string> words;
    std::vector<std::string>::iterator it;
};

我正在尝试使用此功能以相反的顺序打印出单词:

void print_in_reverse(std::string in) {
    WordCrawler wc = WordCrawler(in, true);
    while (!wc.atBeginning()) {
        --wc;
        std::cout << *wc << " ";
    } 
}

我使用以下构造函数构造我的WordCrawler对象:

WordCrawler::WordCrawler(std::string in, bool reversed) {
    std::istringstream iss(in);
    std::string token;
    while (std::getline(iss, token, ' '))
    {
        words.push_back(token);
    }
    if (reversed) {
        it = words.end();
    } else {
        it = words.begin();
    }
}

其余成员函数非常简单:

/**
 True if pointer is at the beginning of vector
 */
bool WordCrawler::atBeginning() const {
    return it == words.begin();
}

/**
  Function that returns the string stored at the pointer's address
 */
std::string WordCrawler::operator*() const {
    return *it;
}

/**
  Function that increments the pointer back by one
 */
WordCrawler& WordCrawler::operator--() {
    if (!atBeginning())
        --it;
    return *this;
}

我发现在Xcode和cpp.sh上一切正常,但是在Visual Studio上,它抛出运行时错误,指出atBeginning()函数的vector iterators incompatible 我的假设是,这是因为代码依赖于某种未定义的行为,但是由于我对C ++比较陌生,所以我不确定它是什么。

我知道, it始终是一个迭代words载体,我知道words后并没有改变it已经被初始化,所以我不知道是什么问题。

完整代码,请访问: http : //codepad.org/mkN2cGaM

您的对象有三个违反规则-在复制/移动构造中,迭代器仍将指向旧对象中的向量。

WordCrawler wc = WordCrawler(in, true); 指定一个复制/移动操作,从而触发此问题。 大多数编译器在这里执行复制省略,但我听说无论如何在调试模式下都不会使用旧版本的MSVC。

为了正确解决此问题,我建议在类中使用索引而不是迭代器。 如果您真的想使用迭代器,则需要实现自己的copy-constructor和move-constructor。

将该行更改为WordCrawler wc(in, true); 可能会修复该特定程序,但相同的问题仍会潜伏,并且可能在以后进行进一步修改时出现。

暂无
暂无

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

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