📜  在C++中的std :: plus

📅  最后修改于: 2021-05-30 02:17:54             🧑  作者: Mango

它是用于执行加法的函数对象。对象类的调用返回添加两个参数的结果(由运算符 +返回)。

句法 :

template  struct plus : binary_function  
{
  T operator() (const T& x, const T& y) const { return x + y; }
};

Template parameters :
T - Type of the arguments and return type of the functional call.
    The type shall support the operation (operator+).

Member types :
x : Type of the first argument in member operator()
y : Type of the second argument in member operator()
result_type : Type returned by member operator()
// C++ program to illustrate std::plus
// by adding the respective elements of 2 arrays
#include  // std::cout
#include  // std::plus
#include  // std::transform
  
int main()
{
    // First array
    int first[] = { 1, 2, 3, 4, 5 };
  
    // Second array
    int second[] = { 10, 20, 30, 40, 50 };
  
    // Result array
    int results[5];
  
    // std::transform applies std::plus to the whole array
    std::transform(first, first + 5, second, results, std::plus());
  
    // Printing the result array
    for (int i = 0; i < 5; i++)
        std::cout << results[i] << " ";
  
    return 0;
}

输出:

11 22 33 44 55 

另一个例子:

// C++ program to illustrate std::plus
// by adding all array elements with a number
#include 
  
int main()
{
    // Array with elements to be added
    int arr[] = { 10, 20, 30 };
  
    // size of array
    int size = sizeof(arr) / sizeof(arr[0]);
  
    // Variable with which array is to be added
    int num = 100;
  
    // Variable to store result
    int result;
  
    // using std::accumulate to perform addition on array with num
    // using std::plus
    result = std::accumulate(arr, arr + size, num, std::plus());
  
    // Printing the result
    std::cout << "The result of 100 + 10 + 20 + 30 is " << result;
  
    return 0;
}

输出:

The result of 100 + 10 + 20 + 30 is 160
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”