vector::at vs. vector::operator[]

前端 未结 8 1782
走了就别回头了
走了就别回头了 2020-11-30 18:37

I know that at() is slower than [] because of its boundary checking, which is also discussed in similar questions like C++ Vector at/[] operator sp

相关标签:
8条回答
  • 2020-11-30 19:22

    I'd say the exceptions that vector::at() throws aren't really intended to be caught by the immediately surrounding code. They are mainly useful for catching bugs in your code. If you need to bounds-check at runtime because e.g. the index comes from user input, you're indeed best off with an if statement. So in summary, design your code with the intention that vector::at() will never throw an exception, so that if it does, and your program aborts, it's a sign of a bug. (just like an assert())

    0 讨论(0)
  • 2020-11-30 19:32

    According to this article, performance aside, it doesn't make any difference to use at or operator[], only if the access is guaranteed to be within the size of the vector. Otherwise, if access is just based on the capacity of the vector it is safer to use at.

    0 讨论(0)
提交回复
热议问题