中級 › terminate called after throwing an instance of 'std::out_of_range' の原因と直し方 › パターン1
terminate called after throwing an instance of 'std::out_of_range' の原因と直し方
std::vectorの範囲外の要素に .at() でアクセスしたときに、例外std::out_of_rangeが投げられ、それを捕まえずにプログラムが終了してしまうバグです。
1 #include <iostream> 2 #include <vector> 3 int main() { 4 std::vector<int> nums = {1, 2, 3}; 5 std::cout << nums.at(__) << std::endl; ^ 6 return 0; 7 }
terminate called after throwing an instance of 'std::out_of_range'
what(): vector::_M_range_check: __n (which is 10) >= this->size() (which is 3)
Aborted
空欄を埋めてコンパイル・実行を通す
.at()は範囲外アクセスを検知するとstd::out_of_range例外を投げます。それを捕まえるtry-catchが無いとプログラム全体がterminateで強制終了します。
次の問題