c++ - 关于 C++ 中的右移运算符 >>

标签 c++

这是我今天看到的一个 C++ 程序:

for (int i = 0; i < LEVELS; ++i)
{
    int pyr_rows = rows >> i;      // what is the usage of >> i here ? 
    int pyr_cols = cols >> i;      // why we what to use it in this way.

    depths_curr_[i].create (pyr_rows, pyr_cols);
}

我比较好奇的是运算符>>在这里的用法。我尝试了一个简单的程序并输入了结果:

    int rows = 5;
int cols = 3;
for (int i=0; i<5; i++)
{
    int pyr_rows = rows >> i;
    std::cout << "current i is:" << i << std::endl;     
    std::cout << "pyr_rows is: " << pyr_rows << std::endl << std::endl;

    int pyr_cols = cols >> i;
    std::cout << "current i is:" << i << std::endl;
    std::cout << "pyr_cols is: " << pyr_cols << std::endl << std::endl;

}

结果是这样的:

current i is:0
pyr_rows is: 5

current i is:0
pyr_cols is: 3

current i is:1
pyr_rows is: 2          // from now on 
                        // the outputs of pyr_rows and pyr_cols are weird to me
current i is:1
pyr_cols is: 1           

current i is:2
pyr_rows is: 1          

current i is:2
pyr_cols is: 0

current i is:3
pyr_rows is: 0

current i is:3
pyr_cols is: 0

current i is:4
pyr_rows is: 0

current i is:4
pyr_cols is: 0

为什么输出是这样的?谁能解释一下?为什么我们要以这种方式使用它?我们更愿意在任何情况下这样做?

最佳答案

它不是“提取运算符”,而是右移运算符,这就是 >>> 在 C++ 开始发明疯狂的重载方法之前的意思。我从 pyr 猜测这是金字塔图像处理?这个想法是每次 i 增加 1 时,金字塔中的行数和列数都减半。这是因为右移 i 基本上是除法(向下舍入)2^i。

关于c++ - 关于 C++ 中的右移运算符 >>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17348801/

相关文章:

c++ - 在 OpenCV 中将灰度图像转换为单色

c++ - 为分数类 C++ 重载 >>

c++ - 使用 extern 的显式实例化声明

c++ - 指针 "this"的地址在指向成员函数调用的指针内意外更改

c++ - 在 C++ 中为两个参数使用 const 覆盖运算符

c++ - 如何使用 opencv 从矩阵 vector 构建图像

c++ - openMP过度同步

c++ - 如何转换一个char表示的十六进制值?

c++ - 当一个变量比 C++ 中的另一个变量保存更少的位/字节时有什么区别

c++ - 理解 as-if 规则, "the program was executed as written"