if语句中的de-reference

时间:2014-09-07 14:23:07

标签: c++ if-statement iterator dereference

在第一个语句中,it被取消引用为0,因为向量中的元素1是0.在我的第二个if语句中,我想在取消引用之前增加it

int function(vector<int>& vec){
    for (auto it = vec.begin() + 1; it != vec.end(); ++it){
        if (*it == 0)
        {
            cout << "element 1 = 0" << endl;
            if (*(it +1) && *(it +2) == 0)
                cout << "element 2 and 3 = 0";
            return 0;
        }
    }
}

int _tmain(int argc, _TCHAR* argv[])
{

    vector<int>grid = { 0, 0, 0, 0, 5, 2, 2, 2, 2 };
    function(grid);

输出:

  

元素1 = 0

目标输出:

element 1 = 0
element 2 and 3 = 0

1 个答案:

答案 0 :(得分:3)

如果要检查两个元素是否等于零,则需要使用:

if (*(it +1) == 0 && *(it +2) == 0)

而不是:

if (*(it +1) && *(it +2) == 0)

对迭代器进行递增或取消引用没有问题,因为vector的迭代器是随机访问的,这允许使用it + n递增它们。

您的代码中还存在一个问题,即递增迭代器可能会超过最后一个元素,这会导致未定义的行为。

相关问题