中級 › terminate called after throwing an instance of 'std::out_of_range' の原因と直し方 › パターン2
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> scores = {70, 80, 90}; 5 std::cout << scores.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 5) >= this->size() (which is 3)
Aborted
空欄を埋めてコンパイル・実行を通す
要素数3のvectorに対して添字5でアクセスすると、5は0〜2の有効範囲を超えているためstd::out_of_rangeが投げられます。
次の問題