C++ std::vector segfault 使用erase() 时,使用pop_back() 和g++ 时ok [英] C++ std::vector segfault when using erase(), ok when using pop_back() with g++

查看:26
本文介绍了C++ std::vector segfault 使用erase() 时,使用pop_back() 和g++ 时ok的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码:

vector<int> myVector;
myVector.push_back(10);
myVector.erase(myVector.end());

此代码在 Windows (VisualStudio) 上编译并运行良好,但在 Linux 上使用 g++ 编译时会导致段错误.用 pop_back 替换 erase 解决了 Linux 上的问题.

This code compiles and runs fine on Windows (VisualStudio), but results in a segfault on Linux when compiled with g++. Replacing erase with pop_back solves the problem on Linux.

有谁知道为什么两个平台上的行为不同,哪些行为被认为是正确的.

Does anyone know why the behaviour is different on the two platforms, and what behaviour to consider correct.

提前致谢!

推荐答案

end() 通常返回数组中的无效位置(超出末尾的位置).

end() typically returns an invalid position in the array (one beyond the end).

pop_back() 删除向量中的最后一项.

pop_back() removes the last item in the vector.

如果你想擦除,你必须做 erase(end() - 1); 这里 end() - 1 返回一个迭代器到最后一项.

If you want to erase, you have to do erase(end() - 1); here end() - 1 returns an iterator to the last item.

erase(end()) 应该调用 UB - 我认为这是正确的...

erase(end()) should invoke UB - which I think is correct...

正如 Martin 指出的,在调用 erase(end() - 1) 之前,检查向量是否为空!

as Martin pointed out, before calling erase(end() - 1), check that the vector is not empty!

这篇关于C++ std::vector segfault 使用erase() 时,使用pop_back() 和g++ 时ok的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆