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

前端 未结 8 1820
走了就别回头了
走了就别回头了 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:14

    The whole point of using exceptions is that your error handling code can be further away.

    In this specific case, user input is indeed a good example. Imagine you want to semantically analyze an XML data-structure which uses indices to refer to some kind of resource you internally store in a std::vector. Now the XML tree is a tree, so your probably want to use recursion to analyze it. Deep down, in the recursion, there might be an access violation by the writer of the XML file. In that case, you usually want to bump out of all the levels of recursion and just reject the whole file (or any kind of "coarser" structure). This is where at comes in handy. You can just write the analysis code as-if the file was valid. The library code will take care of the error detection and you can just catch the error on the coarse level.

    Also, other containers, like std::map, also have std::map::at which has slightly different semantics than std::map::operator[]: at can be used on a const map, while operator[] cannot. Now if you wanted to write container agnostic code, like something that could deal with either const std::vector& or const std::map&, ContainerType::at would be your weapon of choice.

    However, all these cases usually appear when handling some kind of unvalidated data-input. If you are sure about your valid range, as you usually should be, you can usually use operator[], but better yet, iterators with begin() and end().

提交回复
热议问题