首页 > 编程语言 > 详细

C++ transform for_each

时间:2019-06-12 11:05:42      阅读:40      评论:0      收藏:0      [点我收藏+]

标签:继续   iostream   int   main   list   using   lis   push   push_back   

#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
------------------------------------------------------
请按任意键继续. . .

 

C++ transform for_each

标签:继续   iostream   int   main   list   using   lis   push   push_back   

原文:https://www.cnblogs.com/herd/p/11008203.html

(0)
(0)
   
举报
评论 一句话评论(0
0条  
登录后才能评论!
© 2014 designnerd.net 版权所有 鲁ICP备09046678号-4
打开技术之扣,分享程序人生!
             

鲁公网安备 37021202000002号