对于这个小代码:
#include <thread>
#include <iostream>
#include <memory>
#include <vector>
#include <algorithm>
using namespace std;
void do_work(int id)
{
cout<<this_thread::get_id()<<" "<<id<<endl;
}
int main()
{
vector<thread> threads;
for(int i = 0; i < 20; i++)
threads.push_back(thread(do_work, i));
for_each(begin(threads), end(threads), [](thread & t){
t.join();
});
}
选项 1:
for_each(begin(threads), end(threads), [](thread & t){
t.join();
});
选项2:
for_each(begin(threads), end(threads), mem_fn(&thread::join));
问题: 1.哪种用法比较好? 2.
mem_fn
有什么用?你能给一个简单的解释吗?
关于 std::mem_fun 与 lambdas 以及哪个更有效,我发现这个链接对我有帮助; https://tech.jocodoma.com/2019/02/25/Lambdas-as-First-Class-Citizens-in-CPP/ 基本上他们声称 lambdas,从 C++11 / C++17 开始,似乎是更好的解决方案