0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【C++】vectorへのアクセス「operator[]」と「at()」の違いついてChatGPTに聞いてみた

Last updated at Posted at 2025-02-17

目的

C++においてstringやvectorなどの要素へのアクセス方法「operator[]」と「at()」の違いについてChatGPTに聞いてみた。その備忘録として残す。

違い

主な違いは以下の3つである。

  • 境界値チェック
  • 実行速度
  • 用法

詳しく見ていく。

operator[] at()
境界値チェック インデックス範囲外は未定義動作
境界値チェックはしていない
インデックス範囲外アクセスの場合、"std::out_of_range"の例外をスローする。
実行速度 at()より速い operator[]より遅い
用法 パフォーマンス重視 エラー処理が必要

ChatGPTさん曰く、実行速度に関してはエラーチェックの有無で変わるらしい。
また、用法に関してはoperator[]アクセスは競プロなどでよく見かける気がする。
ただ、どちらでアクセスするについても、事前にifで範囲確認行うのが無難であろう。

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?