[英]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.