【STL】常用的operator classes

來源:互聯網
上載者:User
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;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.