當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。