c++ - 矢量迭代器循环使用 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?
解决方案
试试这个为你的迭代
for (auto it = words.rbegin(); it != words.rend(); it++)
推荐阅读
- java - NoClassDefFoundError: org/hibernate/service/ServiceRegistry
- java - selenium/browsermob addheader 不工作 (2.1.5)
- javascript - 使用 jQuery 创建 HTML 链接
- java - 如何启用 Saxon xpath 表达式缓存?
- javascript - d3js v5 + Topojson v3 在点击图例上显示/隐藏元素
- javascript - 下划线过滤多维对象
- websocket - Redis vs dynamoDb 地理定位跟踪
- excel - EXCEL VBA Specialcells 读取行
- react-native - React native Expo TypeError:网络请求失败
- r - 重命名R中列表列表中的列