32
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

vector.at(index)とvector[index]の違い

Last updated at Posted at 2013-10-21

at関数の場合は範囲外を参照したときにエラー(std::out_of_range)になりますが、
[]の場合は普通に配列外参照をし、エラーになりません。

そのため、[]の場合はインデックスの指定をミスしてもとりあえず動き、謎の値が返ってきます。

##サンプルコード

error_sample.cpp
#include <iostream>
#include <vector>
#include <stdexcept>

using namespace std;

int main()
{
  vector<int> array;

  for (int i=0; i<10; i++)
    array.push_back(i);

  cout << "start" << endl;

  try {
    cout << array.at(9) << endl;
    // 例外起きる
    cout << array.at(10) << endl;
  } catch (const out_of_range& oor) {
    // 例外とれる
    cout << "Error " << oor.what() << endl;
  }

  try {
    cout << array[9] << endl;
    // 例外起きないので謎の値が返ってくる
    cout << array[10] << endl;
  } catch (const out_of_range& oor) {
    // 例外とれない
    cout << "Error " << oor.what() << endl;
  }

  cout << "end" << endl;

  return 0;
}

結果

start
9
Error vector::_M_range_check
9
0
end

##参考
http://www.cppll.jp/cppreference/cppvector_details.html#Operators
http://www.cplusplus.com/reference/stdexcept/out_of_range/

32
19
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
32
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?