c++里 对 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个回答

C++里没有map，filter，reduce，这是python的名字
C++的等价物是transform、copy_if、accumulate

``````// 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";
}
``````