【问题标题】:De-reference in if statementif 语句中的取消引用
【发布时间】:2014-10-31 21:39:08
【问题描述】:

在第一个语句中,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

【问题讨论】:

  • 不清楚你在问什么。
  • 抱歉,我已经编辑了我的问题。

标签: c++ if-statement iterator dereference


【解决方案1】:

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

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

代替:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-18
    • 2016-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多