c++中循环的第一个值与其他值不同

first value of a loop in c++ different for the others

本文关键字:其他 第一个 循环 c++      更新时间:2023-10-16

我需要放入循环的第一个值=0,然后使用一个范围来启动循环。

在MatLab中,这是可能的:x=[0-范围:范围](范围是一个整数)这将给出[0,-范围,-范围+1,-范围+2,…,范围-1,范围]的值

问题是我需要用C++来做这件事,我试图用一个数组来做,然后像循环中的值一样输入,但没有成功。

//After loading 2 images, put it into matrix values and then trying to compare each one.   
for r=1:bRows
    for c=1:bCols
        rb=r*blockSize;
        cb=c*blockSize;
    %%for each block search in the near position(1.5 block size)
    search=blockSize*1.5;
    for dr= [0 -search:search] //Here's the problem.
        for dc= [0 -search:search]
            %%check if it is inside the image
            if(rb+dr-blockSize+1>0 && rb+dr<=rows && cb+dc-blockSize+1>0 && cb+dc<=cols)
                %compute the error and check if it is lower then the previous or not
                block=I1(rb+dr-blockSize+1:rb+dr,cb+dc-blockSize+1:cb+dc,1);
                TE=sum( sum( abs( block - cell2mat(B2(r,c)) ) ) );
                if(TE<E) 
                    M(r,c,:)=[dr dc]; %store the motion vector
                    Err(r,c,:)=TE;    %store th error 
                    E=TE;
                end
            end
        end
    end
    %reset the error for the next search
     E=255*blockSize^2;
end

结束

C++本机不支持您从MatLab了解到的那种范围,尽管外部解决方案是可用的,如果对您的用例来说有些过头的话。但是,C++允许您使用该语言提供的基元(如for循环和可调整大小的数组)轻松(高效)地实现它们。例如:

// Return a vector consisting of
// {0, -limit, -limit+1, ..., limit-1, limit}.
std::vector<int> build_range0(int limit)
{
  std::vector<int> ret{0};
  for (auto i = -limit; i <= limit; i++)
    ret.push_back(i);
  return ret;
}

生成的矢量可以很容易地用于迭代:

for (int dr: build_range0(search)) {
  for (int dc: build_range0(search)) {
    if (rb + dr - blockSize + 1 > 0 && ...)
    ...
  }
}

当然,上面的内容浪费了一些空间来创建一个临时向量,结果却把它扔掉了(我怀疑在您的MatLab示例中也会发生这种情况)。如果只想迭代这些值,则需要将循环(如build_range0中的循环)直接包含在函数中。这可能会降低可读性并引入重复。为了保持代码的可维护性,您可以将循环抽象为一个通用函数,该函数接受带有循环体的回调:

// Call fn(0), fn(-limit), fn(-limit+1), ..., fn(limit-1), and fn(limit)
template<typename F>
void for_range0(int limit, F fn) {
  fn(0);
  for (auto i = -limit; i <= limit; i++)
    fn(i);
}

上述函数可以通过提供匿名函数的循环体来实现迭代:

for_range0(search, [&](int dr) {
  for_range0(search, [&](int dc) {
    if (rb + dr - blockSize + 1 > 0 && ...)
    ...
  });
});

(请注意,这两个匿名函数都通过引用捕获封闭变量,以便能够对它们进行变异。)

阅读您的评论,您可以执行类似的操作

for (int i = 0, bool zero = false; i < 5; i++)
{
    cout << "hi" << endl;
    if (zero)
    {
        i = 3;
        zero = false;
    }
}

这将从0开始,然后在做了我希望它做的事情之后,给我赋值3,然后在每次迭代中继续添加。