C++常用新特性

匿名 (未验证) 提交于 2019-12-03 00:33:02

C++常用新特性,持续更新……
1. std::for_each、std::mem_fn

#include <algorithm>  // std::for_each #include <functional> // std::mem_fn #include <iostream> #include <vector> #include <thread>  struct MfFe {     int m_a;     int m_b;      int sum(int i, int j)     {         return i + j;     }      int tuple(int i)     {         return i*3;     } };  int square(int i) {     std::cout << i * i << std::endl;     return i * i; }  int multiply(int i,int j) {     std::cout << i * j << std::endl;     return i * j; }  int main() {     std::vector<std::thread> vecth;     for (int i = 0; i!=10; ++i)     {         vecth.push_back(std::thread(multiply,i,i+1));     }     std::for_each(vecth.begin(), vecth.end(), std::mem_fn(&std::thread::join));      /* 在std::for_each中调用square */     std::vector<int> avec;     for (int i = 0; i!=10;++i)     {         avec.push_back(i);     }     /* 解引avec.begin()作为square的参数 */     std::for_each(avec.begin(), avec.end(), square);      /* 此处不能模仿L42的用法使用std::mem_fn(&MfFe::tuple),因此下面这句是错误的 */     //std::for_each(avec.begin(), avec.end(), std::mem_fn(&MfFe::tuple));      /* 使用std::mem_fn进行函数调用,std::mem_fn的参数必须是类函数 */     MfFe amf{ 1,2 };     auto fn = std::mem_fn(&MfFe::sum);     std::cout << fn(amf, amf.m_a, amf.m_b) << std::endl;      system("pause"); }
文章来源: C++常用新特性
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!