What are the benefits of using vector :: at over vector :: operator []? When should you use the vector :: instead, and not the vector :: size + vector :: operator []?
The important point here is that exceptions allow you to separate the normal code flow from the error processing logic, and one blocking block can handle problems that arise from any of the myriad throw sites, even if they are scattered inside function calls. So, it's not that at() necessarily easier for one use, but sometimes it gets easier - and less obfuscated normal logic - when you have a lot of indexing to check.
It should also be noted that in some types of code the index is incremented in complex ways and is constantly used to search for an array. In such cases, it is much easier to provide the correct checks with at() .
As a real-life example, I have code that tokens C ++ in lexical elements, and then another code that moves the index along the token vector. Depending on what happened, I can enlarge and check the following element, as in:
if (token.at(i) == Token::Keyword_Enum) { ASSERT_EQ(tokens.at(++i), Token::Idn); if (tokens.at(++i) == Left_Brace) ... or whatever
In such a situation, it is very difficult to check if you have not improperly reached the end of the input, because it is very dependent on the exact tokens. Explicit verification at each point of use is painful, and there is much more room for a programmer's error, since increments before / after, offsets at the point of use, erroneous discussions about the continued validity of some earlier tests, etc. Click.
Tony Delroy Feb 21 '12 at 10:43 2012-02-21 10:43
source share