提问人:MK4 提问时间:10/24/2023 最后编辑:273KMK4 更新时间:10/24/2023 访问量:37
为什么std::cin在以下情况下会给我一个段错误?[复制]
Why does std::cin give me a seg-fault in the following case? [duplicate]
问:
这个问题在这里已经有答案了:
像 some_container.rend() 一样使用 std::p rev(vector.begin()) 或 std::next(vector.begin(), -1) 作为反向哨兵是否安全? (3 个答案)
上个月关闭。
下面的代码在第二行中显示了一个分段错误。我不知道为什么?
string str;
cin >> str; //Problem!!!
list<char> L;
for(char s: str) L.push_back(s);
auto it = L.begin();
while(it != prev(L.begin())){
if(*(it) == 'A' && *(next(it)) == 'B'){L.erase(it, next(next(it)));}
else it++;
}
cout << str << endl;
答: 暂无答案
评论
prev(L.begin())
表现出未定义的行为。显然之前没有迭代器begin()
L.erase(it, next(next(it)))
无效。之后使用它的任何尝试都会表现出未定义的行为。it
prev(it),
it== end()
表示next(it)。
std::cin