考虑这个代码
#include <vector>
#include <iostream>
main()
{
std::vector <int> x(1);
for(int q=0;; q++)
{
int y = x[q];
std::cout << q << " ";
}
}
在我的g++系统上,在使用Segmentation fault (core dumped)
崩溃之前,它最多可打印32570。大概需要这么长的时间,因为-32570是操作系统和/或分配器将分配给向量的最小内存块的大小。但当然,任何时候我们在数组结束后执行这样的操作通常都是一个错误。因此,如果我能在出现这种情况时让程序退出并显示一条有用的错误消息,那就太好了。
几年前,在Xcode中,我回忆起发生在它将以std::vector
的类型(和名称?)退出的地方的行为。目前我在Linux上使用g++。有没有沿着这些路线(或其他什么)的解决方案?
使用-D_GLIBCXX_DEBUG
编译以启用STL容器中的调试模式。
或者,您也可以使用__gnu_debug
命名空间中的特定调试容器,例如__gnu_debug::vector
:
#include <iostream>
#include <debug/vector>
int main()
{
__gnu_debug::vector <int> x(1);
for(int q = 0; ; q++)
{
int y = x[q];
std::cout << q << " ";
}
}
您可以使用std::vector::at
成员函数,如果您的索引违反了向量的范围,该函数会引发out_of_range
异常。
#include <vector>
#include <iostream>
int main() {
std::vector <int> x(1);
for(int q=0;; ++q) {
int y = x.at(q);
std::cout << q << " ";
}
}