• C++ transform for_each


    #include<iostream>
    #include<vector>
    #include <list>
    #include <algorithm>
    #include <functional>

    using namespace std;

    //不需拷贝,速度快
    void square(int &elementParam)
    {
      elementParam = elementParam*elementParam;
    }

    //速度慢,传参数一次拷贝,返回时一次拷贝
    int square2(int elementParam)
    {
      return elementParam*elementParam;
    }

    int main()
    {
      vector<int> vec2;
      vector<int> vec3;

      for (int k=0;k<10;k++)
      {
        vec2.push_back(k);
        vec3.push_back(k);
      }

      for_each(vec2.begin(),vec2.end(),square);


      for (auto vec_iter2 = vec2.begin(); vec_iter2 != vec2.end(); ++vec_iter2)
      {
        cout << *vec_iter2 << " ";
      }
      cout << endl;
      cout << "------------------------------------------------------" << endl;


      for (auto vec_iter3 = vec3.begin(); vec_iter3 != vec3.end(); ++vec_iter3)
      {
        cout << *vec_iter3 << " ";
      }
      cout << endl;
      cout << "------------------------------------------------------" << endl;

      transform(vec3.begin(),vec3.end(),vec3.begin(),square2);
      for (auto vec_iter3 = vec3.begin(); vec_iter3 != vec3.end(); ++vec_iter3)
      {
        cout << *vec_iter3 << " ";
      }
      cout << endl;
      cout << "------------------------------------------------------" << endl;

      //transform 比 for_each灵活

           //for_each比transform速度快 


      system("pause");
      return 0;
    }

    =====================================================

    0 1 4 9 16 25 36 49 64 81
    ------------------------------------------------------
    0 1 2 3 4 5 6 7 8 9
    ------------------------------------------------------
    0 1 4 9 16 25 36 49 64 81
    ------------------------------------------------------
    请按任意键继续. . .

  • 相关阅读:
    分布式哈希和一致性哈希算法
    消息队列rabbitmq的五种工作模式(go语言版本)
    Mysql查询缓存
    数据库的三大设计范式
    二叉树的常见算法
    消息队列选型分析
    Mysql防止索引失效原则
    Mysql索引优化单表、两表、三表实践
    数据结构 【栈与队列】
    谷歌实用插件
  • 原文地址:https://www.cnblogs.com/herd/p/11008203.html
Copyright © 2020-2023  润新知