我经常想确保我在函数体的顶部有一次在边界内。 我这样做的不同方法是:
// 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 corrective action ...
}
if( v.size() <= idx )
{
// take corrective action ..
}
在第二种和第三种方法(可能还有其他方法)之间,哪种方法效率更高?
最佳答案
就用
idx < vec.size()
并完成它。在这个问题上多花一分钟不会让您的应用程序任何更快。
另外,考虑检查访问:
try {
vec.at(idx) = stuff;
} catch (std::out_of_range& err) {
// oh dear god
}
关于c++ - 检查 std::vector 索引是否超出范围的最快方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7395161/