您的位置:首页 > 运维架构

常用的operator classes

2015-06-09 10:35 357 查看
[cpp] view
plaincopyprint?

void test_plus()  

{  

    // 数组与数组之间求和  

    int first[] = {1, 2, 3, 4, 5};  

    int second[] = {10, 20, 30, 40, 50};  

    int results[5];  

    transform(first, first + 5, second, results, std::plus<int>());  

  

    std::copy(first, first + 5, std::ostream_iterator<int>(std::cout, " "));  

    std::cout << std::endl;  

  

    // 数组累计求和  

    int i[] = {1, 2, 3, 4, 5, 6};  

    int sum(0);  

    sum = accumulate(i, i + 6, 0, std::plus<int>());  

    std::cout << "The result of 1 + 2 + 3 + 4 + 5 + 6 = " << sum << std::endl;  

}  

  

void test_minus()  

{  

    int numbers[] = {10, 20, 30};  

    int result;  

    result = accumulate(numbers, numbers + 3, 100, std::minus<int>());  

    std::cout << "The result of 100 - 10 - 20 - 30 = " << result << std::endl;  

}  

  

void test_multi()  

{  

    int numbers[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};  

    int result;  

    result = accumulate(numbers, numbers + 10, 1, std::multiplies<int>());  

    std::cout << "The result of 1*2*3*4*5*6*7*8*9*10 = " << result << std::endl;  

  

    // 可以做成阶乘  

    int factorials[10];  

    partial_sum(numbers, numbers + 10, factorials, std::multiplies<int>());  

    std::copy(factorials, factorials + 10, std::ostream_iterator<int>(std::cout, "\n"));  

      

  

//  for (int i = 0; i < 10; ++i)  

//      std::cout << numbers[i] << "! is " << factorials[i] << std::endl;  

}  

  

void test_divides()  

{  

    int first[] = {10, 40, 90, 40, 10};  

    int second[] = {1, 2, 3, 4, 5};  

    int results[5];  

    transform(first, first + 5, second, results, std::divides<int>());  

    std::copy(results, results + 5, std::ostream_iterator<int>(std::cout, " "));  

    std::cout << std::endl;  

}  

  

void test_greater()  

{  

    int numbers[] = {10, 40, 90, 50, 20};  

    std::vector<int> v(numbers, numbers + 5);  

    std::sort(v.begin(), v.end(), std::greater<int>());  

    std::copy(v.cbegin(), v.cend(), std::ostream_iterator<int>(std::cout, " "));  

}  

  

// logical_and, logical_or, logical_not应用基本类似.  

void test_logical_and()  

{  

    bool foo[] = {true, false, true, false};  

    bool bar[] = {true, true, false, false};  

    bool result[4];  

    transform(foo, foo+4, bar, result, std::logical_and<bool>());  

    std::cout << std::boolalpha << "Logical AND:\n";  

    for (int i = 0; i < 4; ++i)  

        std::cout << foo[i] << " AND " << bar[i] << " = " << result[i] << std::endl;  

}  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: