首页 > 解决方案 > 矢量迭代器循环使用 g++ 而不是 VisualC++,为什么?

问题描述

我有一个我在我的 linux 机器上编写的程序。它使用一个std::vector<std::string>,我用一个 for 循环来循环它,就像这样

std::vector<std::string> words;
words.push_back("A");
words.push_back("B");
words.push_back("C");
// loop
for (auto it = words.end(); it >= words.begin(); it--)
{
    std::string word = *it; // invalid deref?
    // do things with word
    if (word == "B")
    {
        words.erase(it);
    }
    std::cout << word << std::endl;
}

int i = 0;
for (std::string word : words)
{
    std::cout << i++ << word << std::endl;
}

这使用 g++ 作为编译器按预期运行,打印 C、B 和 A。但是,当我使用 VisualStudio 运行它时,我得到一个无效的取消引用异常。

我向后遍历向量,因为我想从中删除项目,如果向前循环,这会与迭代器混淆。
我有一个使用整数并使用 获取项目的解决方法std::vector<std::string>.at(int),但我很好奇为什么这适用于我的 linux 机器而不适用于 windows?

标签: c++for-loopvectoriteratorindexoutofboundsexception

解决方案


试试这个为你的迭代

for (auto it = words.rbegin(); it != words.rend(); it++)

推荐阅读