矢量迭代器循环可用于g ++,但不适用于VisualC ++,为什么?

问题描述 投票:0回答:1

我有一个在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-loop vector iterator indexoutofboundsexception
1个回答
1
投票

尝试此操作进行迭代

for (auto it = words.rbegin(); it != words.rend(); it++)
© www.soinside.com 2019 - 2024. All rights reserved.