当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


C++ std::bit_or用法及代码示例


bit_or是C++中的内置函数,用于执行bitwise_or并在对其参数应用bitwise_or操作后返回结果。

头文件:

#include <functional.h>

模板类别:

template <class T> struct bit_or;

参数:它接受参数T,它是函数调用要比较的参数的类型。

Note:



  1. 此类的对象可用于标准算法,例如变换或累加。
  2. 成员函数('operator()')返回其参数的bitwise_or。

我们必须包括库‘functional’和‘algorithm’才能分别使用bit_or和transform()。

下面是C++中bit_or的图示:

问题一:

// C++ program to show the 
// functionality of bit_or 
  
#include <algorithm> // to include transform 
#include <functional> // to include bit_or 
#include <iostream> 
#include <iterator> 
using namespace std; 
  
int main() 
{ 
    // declaring the values 
    int xyz[] = { -7, 2, 5, 100, 1029 }; 
    int abc[] = { -4, 0, 5, 1, 1 }; 
    int n = 5; 
    // defining results 
    int results[n]; 
  
    // transform is used to apply 
    // bitwise_or on the arguments 
    transform(xyz, end(xyz), abc, 
              results, bit_or<int>()); 
  
    // printing the resulting array 
    cout << "Results:"; 
    for (const int& x:results) 
        cout << ' ' << x; 
  
    return 0; 
}
输出:
Results:-3 2 5 101 1029

Some points to Remember

  1. Bitwise_or of a number with zero results into the number itself.
  2. Bitwise_or of two same numbers is also equal to that number itself
  3. If the number is odd it’s bit_or with 1 will result into same number
  4. If the number is even it’s bit_or with 1 will always results into “number+1”

问题2:

// C++ program to show the 
// functionality of bit_or 
  
#include <algorithm> 
#include <functional> 
#include <iostream> 
#include <iterator> 
using namespace std; 
  
int main() 
{ 
    // declaring the values 
    // in form of hexadecimals 
    int xyz[] = { 0, 1100 }; 
    int abc[] = { 0xf, 0xf }; 
  
    // defining results 
    int results[2]; 
  
    // transform is used to apply 
    // bitwise_or on the arguments 
    transform(xyz, end(xyz), abc, 
              results, bit_or<int>()); 
  
    // printing the resulting array 
    cout << "Results:"; 
    for (const int& x:results) 
        cout << ' ' << x; 
  
    return 0; 
}
输出:
Results:15 1103

参考: https://en.cppreference.com/w/cpp/utility/functional/bit_or




相关用法


注:本文由纯净天空筛选整理自karan_gandhi大神的英文原创作品 std::bit_or in C++ with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。