饭来 2019-05-02 13:52 采纳率: 100%
浏览 1386
已采纳

c++里 对 map, filter,reduce的应用

对一串整数应用map,filter,reduce进行转化
L1= [x1,x2,...,x20]
1.用map求出这组数绝对值的3倍, L2= [3|x1|,3|x2|,...,3|xn|]
3.用filter筛选出L2里的2位数并且是奇数,生成L3
4.用reduce选出L3的最小数,和L3里数字的最大公约数,用空格隔开两个数字并输出

Sample input:
-5, -24, -123, -81, 200, 157, 84, 67, -83, -60, -72, 192, -25, -20, -50, -181, -70, -15, -108, -123

L1 = [15, 72, 369, 243, 600, 471, 252, 201, 249, 180, 216, 576, 75, 60, 150, 543, 210, 45, 324, 369]

L2= [15, 75, 45].

Sample output: 15 15

  • 写回答

1条回答

  • threenewbee 2019-05-02 16:45
    关注

    C++里没有map,filter,reduce,这是python的名字
    C++的等价物是transform、copy_if、accumulate
    如果你需要用map,filter,reduce,可以对这三个函数再包装一次

    图片说明

    // Q759592.cpp : This file contains the 'main' function. Program execution begins and ends there.
    //
    
    #include <iostream>
    #include <algorithm>
    #include <vector>
    #include <numeric> 
    
    using namespace std;
    
    int getgcd(int a, int b)
    {
        for (int i = a > b ? b : a; i >= 1; i--)
        {
            if (a % i == 0 && b % i == 0)
                return i;
        }
        return 1;
    }
    
    int main()
    {
        vector<int> L1 { -5, -24, -123, -81, 200, 157, 84, 67, -83, -60, -72, 192, -25, -20, -50, -181, -70, -15, -108, -123 };
    
        vector<int> L2;
    
        copy_if(L1.begin(), L1.end(), std::back_inserter(L2),
            [](int d) { return 1; });
    
        transform(L2.begin(), L2.end(), L2.begin(),
            [](int d) -> int { return d > 0 ? d * 3 : (-d) * 3; });
    
        for (auto value : L2)
        {
            cout << value << " ";
        }
    
        cout << "\n";
    
        vector<int> L3;
    
        copy_if(L2.begin(), L2.end(), std::back_inserter(L3),
            [](int d) { return (d >= 10 && d <= 99 & d % 2); });
    
        for (auto value : L3)
        {
            cout << value << " ";
        }
    
        cout << "\n";
    
        int min = accumulate(L3.begin(), L3.end(), L3[0],
            [](int d, int c) { return c > d ? d : c; });
    
        cout << min;
    
        int gcd = accumulate(L3.begin(), L3.end(), L3[0],
            [](int d, int c) { return getgcd(d, c); });
    
        cout << " " << gcd;
    
        cout << "\n"; 
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器