自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

C++代碼賞析:Map、Filter、Reduce

開發(fā) 前端
函數(shù)式編程中的 map、reduce、filter,它們都是一種控制。而參數(shù) lambda 是邏輯(我們要解決的問題),它們一起組成了一個(gè)算法。最后,我再把數(shù)據(jù)放在數(shù)據(jù)結(jié)構(gòu)里進(jìn)行處理,最終就成為了我們的程序。

概念

出自Google的論文《MapReduce: simplified data processing on large clusters》,MapReduce是一種編程模型,用于大規(guī)模數(shù)據(jù)集(大于1TB)的并行運(yùn)算。概念"Map(映射)"和"Reduce(歸約)",是它們的主要思想,都是從函數(shù)式編程語言里借來的,還有從矢量編程語言里借來的特性。它極大地方便了編程人員在不會(huì)分布式并行編程的情況下,將自己的程序運(yùn)行在分布式系統(tǒng)上。

  • 程序 = 算法 + 數(shù)據(jù)結(jié)構(gòu)
  • 算法 = 控制 + 邏輯
  • 程序復(fù)雜度 = 控制復(fù)雜度(可降低) + 邏輯復(fù)雜度(理論下限)
  • 架構(gòu)或設(shè)計(jì)目的就是分離控制和邏輯

函數(shù)式編程中的 map、reduce、filter,它們都是一種控制。而參數(shù) lambda 是邏輯(我們要解決的問題),它們一起組成了一個(gè)算法。最后,我再把數(shù)據(jù)放在數(shù)據(jù)結(jié)構(gòu)里進(jìn)行處理,最終就成為了我們的程序。

注:vegetarian 素食主義者


C++

map

std::transform

filter

std::remove_if

reduce

std::accumulate

例子

  1. 過濾出奇數(shù)
  2. 把上一步計(jì)算結(jié)果分別做平方處理
  3. 把上一步的結(jié)果進(jìn)行求和
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>

using namespace std;

int main(){
std::vector<int> nums{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };
std::vector<int> cache (nums.size());

// filter
auto it = std::copy_if (nums.begin(),
nums.end(),
cache.begin(),
[](int n){return n % 2 == 1;});
// shrink container to new size
cache.resize(std::distance(cache.begin(),it));

// map
std::transform(cache.begin(),
cache.end(),
cache.begin(),
[](int n) -> int {return n * n; });

auto result = std::accumulate(cache.begin(),
cache.end(),
0,
[] (int carry, int n){ return carry + n;});

std::cout << result << std::endl;

return 0;
}

在線測(cè)試

https://wandbox.org/permlink/yqa3d46oSx2GnVoQ


責(zé)任編輯:武曉燕 來源: 今日頭條
相關(guān)推薦

2023-01-26 23:44:41

C++代碼生命周期

2024-01-10 08:47:48

Python函數(shù)Map()

2024-11-08 12:42:34

Rustmapfilter

2024-06-04 00:20:00

Python函數(shù)

2024-07-11 12:14:20

Pythonmapfilter

2025-04-11 08:00:00

函數(shù)式編程Python

2010-06-03 16:46:23

Hadoop Map-

2023-10-30 10:29:50

C++最小二乘法

2024-08-19 00:01:00

2011-05-18 18:05:47

C#C++

2010-01-18 16:17:53

C++代碼

2010-01-14 14:40:21

C++代碼

2011-05-18 17:56:38

C#C++

2010-01-21 10:23:53

C++代碼

2017-03-28 21:25:19

無循環(huán)代碼JavaScript

2014-03-18 10:16:58

SVM

2010-01-22 13:45:36

C++代碼

2023-01-05 08:55:00

2013-09-05 09:50:11

C++代碼優(yōu)化

2010-02-05 10:23:09

C++基本函數(shù)
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)