矢量走出边界,而不给出错误 [英] Vector going out of bounds without giving error
本文介绍了矢量走出边界,而不给出错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 std :: vector
。我检查它的大小是6,但是当我尝试访问 vec [6]
以检查它是否会给错误,我得到没有错误,但有一些数字。不应该出现错误吗?
I have a std::vector
. I check its size which is 6 but when I try to access vec[6]
to check whether it will give error, I get no error but some number instead. Should not it give an error?
编辑:例如:
struct Element
{
std::vector<double> face;
};
int main()
{
Element elm;
.... // insert 6 elements into elm.face
std::cout << elm.face.size() << std::endl; // answer is 6
std::cout << elm.face[6] << std::endl; // answer is some number
}
推荐答案
STL向量在调用 .at()
成员函数时执行边界检查,但不对 []
运算符执行任何检查。
STL vectors perform bounds checking when the .at()
member function is called, but do not perform any checks on the []
operator.
当超出范围时, []
运算符产生未定义的结果。
When out of bounds, the []
operator produces undefined results.
这篇关于矢量走出边界,而不给出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文