开发者

What is the fastest way to check if std::vector index is not out of bounds?

开发者 https://www.devze.com 2023-04-04 15:13 出处:网络
Often I want to make sure I am in bounds once at the top of my function body. The different ways I do this are:

Often I want to make sure I am in bounds once at the top of my function body. The different ways I do this are:

// I don't like this much as it stops the program when I may not want to
assert( idx < v.size() );

if( !(idx < v.size()) )
{
    // take 开发者_StackOverflowcorrective action ...
}

if( v.size() <= idx )
{
    // take corrective action ..
}

Between the second and third method (and maybe others), which is more efficient?


Just use

idx < vec.size()

and be done with it. You're not going to make your application any faster by spending another minute on this issue.

Also, consider checked access:

try {
    vec.at(idx) = stuff;
} catch (std::out_of_range& err) {
    // oh dear god
}


Most of the time you are not going to check. Because you have already validated the user input at the point where it enters the program thus you should not need to check anywhere else.

If there is any possibility that unvalidated input is being used then you should be using the method at(). This will throw an exception if the index is out of bounds and behave like operator[] in all other situations. The exception will cause the application to quit unless you explicitly catch and compensate (which you should only do if that is a valid option otherwise let the application exit (maybe with an error message if appropriate)).

Personally I much prefer to use exception instead of asserts().
Asserts can be turned off at the compiler level (so they are useless in production code (only good for testing the code is valid in unit tests)), exceptions provide the same functionality (quick shut down of the application if they are triggered (and like exceptions they allow you to log info)). Unlike asserts exceptions can be caught if appropriate (though mostly you just want to let them kill the application)).


I assume you're looping over this vector. If the function for which you're writing this code isn't being called in a loop or something, just don't worry about it. Both statements compile to the same 3 or 4 instructions, depending on your compiler's vector implementation. If the function IS being called in a loop, do two things: make it inline, and get rid of the check. Instead, check the index against the boundary in the calling function.

Also, just don't worry about it, because something else is your bottleneck. Look at your API calls, use of virtual functions in loops, float to int casts, sort procedures, thread synchronizations... trust me, this isn't going to hurt.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号