c++ lambda expression pass parameters

发布时间 2023-06-27 14:50:10作者: Fred1987
#include <algorithm>
#include <chrono>
#include <cstdint>
#include <execution>
#include <fstream>
#include <iostream>
#include <random>
#include <uuid/uuid.h>
#include <vector>

char *uuid_value = (char *)malloc(40);
char *get_uuid_value()
{
    uuid_t new_uuid;
    uuid_generate(new_uuid);
    uuid_unparse(new_uuid, uuid_value);
    return uuid_value;
}

std::random_device rd;
std::mt19937_64 mt{rd()};

template <typename T>
T gen_random(T min, T max)
{
    std::uniform_int_distribution<T> uid(min, max);
    return uid(mt);
}

auto la = [](int x, std::string str)
{
    std::cout << "num:" << x << std::endl;
    std::cout << "str:" << str << std::endl;
};



void for_each_parallel_log_file(const std::string &file_name)
{
    //  std::vector<int> vec = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    // std::for_each(
    //     std::execution::par, vec.begin(), vec.end(), [&file_name,&num](int x)
    //     {
    //         std::cout<<"x:"<<x<<",fn:"<<file_name<<",num:"<<num<<std::endl;
    //     });

    std::vector<int> vec = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    std::for_each(std::execution::par, vec.begin(), vec.end(), [&file_name](int x)
        {            
            std::fstream w_file(file_name, std::ios::app);
            if (!w_file.is_open())
            {
                std::cout << "Create or open " << file_name << " failed!" << std::endl;
                return;
            }
            std::stringstream ss;
            int start_point=(x-1)*100000;
            for(int i=0;i<100000;i++)
            {
                ss<<++start_point<<","<<get_uuid_value()<<std::endl;
            }
            w_file<<ss.str();
            ss=std::stringstream();
            w_file.close();
            std::cout<<"Loop:"<<x<<" write finished in "<<file_name<<std::endl; 
        }
        );
} 

int main(int args, char **argv)
{
    la(atoi(argv[1]),argv[2]);
    // for_each_parallel_log_file(argv[1]);
}

 

g++-12 -std=c++2a -I. *.cpp -o h1 -luuid