Why is using “vector.at(x)” better than “vector[x]” in C++?

前端 未结 4 1449
说谎
说谎 2020-12-09 15:20

If I want to get to a value in vector I can use two options : use the [] operator. Or I might use the function .at example for using :

vector ive         


        
4条回答
  •  暖寄归人
    2020-12-09 16:04

    The only difference between at and [] is that at performs a range check, and [] does not. If you have checked the range already or have constructed your index in such a way that it cannot get out of range, and need to access an item repeatedly, you could save a few CPU cycles by opting for [] instead of an at.

    Example of a single check and multiple accesses:

    size_t index = get_index(vect);
    if (index < 0 || index >= vect.size()) return;
    if (vect[index] > 0) {
        // ....
    } else if (vect[index] > 5) {
        // ....
    } else ....
    

    Example of a case when the index is constructed to be inside limits:

    for (size_t i = 0 ; i != vect.size() ; i++) {
        if (vect[i] > 42) {
            // ....
        }
    }
    

提交回复
热议问题