c++中循环的第一个值与其他值不同
first value of a loop in c++ different for the others
我需要放入循环的第一个值=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,然后在每次迭代中继续添加。
相关文章:
- 为什么它只打印双链接列表的第一个值,而我的程序却崩溃了
- std::find,返回所有找到的值的替代方法,而不仅仅是存在重复的向量的第一个值
- 如何仅读取文本文件中的第一个值
- 在C++中,如何在第一个"system()"结束后执行第二个"system()"?
- 查找不在标准中的第一个值::设置<int>最小-最大值
- C++:忽略第一个 cin.ignore 之后的输入
- 在C++中打印多个矢量的第一个值
- C++去除前x个元素的有效方法,在不改变向量大小的情况下将第x+1个元素推到第一个
- C++第一个cout将不会打印
- 我们可以在第一个else-if条件结束后使用另一个else-if条件吗
- OpenGL:第二个VBO破坏了第一个VBO
- 为什么第一个Dynamic_cast没有投射到基类?
- OpenGL 2D游戏只绘制第二个精灵纹理而不是第一个
- C++ 为什么程序只读取第一个值
- 在我的第一个C++程序中需要一些帮助(简单)
- 为什么我的代码在第一个 if 语句处中断?
- 是否可以从另一个类对象调用一个类函数而不继承第一个类
- 无法使我的第一个Windows OpenGL窗口抬起并运行
- 将参数初始化为构造函数,而不是第一个
- 当我超过第一个 getline() 的输入中的数组大小时,第二个 getline 或其他输入函数不起作用