STL源碼剖析 數值算法 accumulate | adjacent_difference | inner_product | partial_sum | power | itoa


//版本1
template <class InputIterator,class T>
T accumulate(InputIterator first,InputIterator last,T init){for(;first != last; ++first){init += *first; //將每個元素數值累加到init身上}return init;
}//版本2
template <class InputIterator,class T,class BinaryOperation>
T accumulate(InputIterator first,InputIterator last,T init,BinaryOperation binary_op){for(;first!=last;++first){init = binary_op(init, *first);//對每一個元素執行二元操作}return init;
}
  • accumulate用于計算init和[first , last)內部所有元素的總和。需要提供一個init,表示當[first,last)為空的區間仍然可以獲取一個明確定義的數值,如果想獲得[first,last)內所有數值的總和,應將init設為0
  • 二元操作符不必滿足交換律和結合律,是的accumulate的行為順序有著明確的定義:先將init初始化,然后針對[first,last)區間內的每一個迭代器i,依次執行init = init + *i(第一版本) 或者 init = binary_op(init, *i) (第二版本)

使用例子

#include <iostream>   //std::cout
#include <functional> //std::minuc
#include <numeric>    //std::accumulateint my_function(int x,int y){return x + 2*y;}
struct my_class{int operator()(int x,int y){return x + 3*y;}
}my_object;int main(){int init = 100;int numbers[] = {10,20,30};
//    std::cout << << std::endl;std::cout << "using default accumulate" << std::endl;std::cout << std::accumulate(numbers,numbers+3,init) << std::endl;std::cout << "using functional's accumulate" << std::endl;std::cout << std::accumulate(numbers,numbers+3,init,std::minus<int>()) << std::endl;std::cout << "using custom function" << std::endl;std::cout << std::accumulate(numbers,numbers+3,init, my_function) << std::endl;std::cout << "using custom object" << std::endl;std::cout << std::accumulate(numbers,numbers+3,init, my_object) << std::endl;}

adjacent_difference

  • 用于計算[first,last)中相鄰元素的差額
  • 將*first 賦值給*result,并針對[first+1,last)內的每個迭代器i 將*i-*(i-1)的數值賦值給*(result+(i-first))
  • 使用就地方式 也就是讓result 等于first 函數為質變算法
  • 存儲第一元素的數值然后存儲后繼元素的差值,便可=可以重建輸入區間的原始內容
  • adjacent_difference 和 partial_sum互為逆運算,如果對區間1 2 3 4 5 執行adjacent_difference結果為1 1 1 1 1,如果對這個結果執行partial_sum 便會得到原始的區間數值為1 2 3 4 5
#include <iostream>   //std::cout
#include <functional> //std::minuc
#include <numeric>    //std::adjacent_differencetemplate <class InputIterator,class OutputIterator>
OutputIterator adjacent_difference(InputIterator first,InputIterator last,OutputIterator result){if(first != last){typename std::iterator_traits<InputIterator>::value_type val,prev;*result = prev = *first;while (++first != last){val = *first;*++result = val - prev; //*++result = binary_op(val,prev);prev = val;}++result;}return result;
}template <class InputIterator,class OutputIterator,class BinaryOperation>
OutputIterator adjacent_difference(InputIterator first,InputIterator last,OutputIterator result,BinaryOperation binary_op){if (first!=last){typename std::iterator_traits<InputIterator>::value_type val,prev;*result = prev = *first;while(++first != last){val = *first;*++result = binary_op(val,prev);prev = val;}}return result;
}//int my_function(int x,int y){return x + 2*y;}
//struct my_class{
//    int operator()(int x,int y){
//        return x + 3*y;
//    }
//}my_object;int myop(int x,int y){return x+y;
}int main(){int val[] = {4,2,3,5,9,11,12};int result[7];std::adjacent_difference(val,val+7,result);std::cout << "using default adjacent_difference" << std::endl;for (int i = 0; i < 7; ++i) {std::cout << result[i] << ' ';}std::cout << std::endl;std::adjacent_difference(val,val+7,result,std::multiplies<int>());std::cout << "using functional operation multiplies" << std::endl;for (int i = 0; i < 7; ++i) {std::cout << result[i] << ' ';}std::cout << std::endl;std::adjacent_difference(val,val+7,result, myop);std::cout << "using custom function" << std::endl;for (int i = 0; i < 7; ++i) {std::cout << result[i] << ' ';}std::cout << std::endl;//    using default adjacent_difference
//    4 -2 1 2 4 2 1
//    using functional operation multiplies
//    4 8 6 15 45 99 132
//    using custom function
//    4 6 5 8 14 20 23}

inner_product

  • 執行兩個序列的一般內積
  • 算法計算 [first1,last1) 和 [first2,first2 + (last1 - first1))的一般內積
  • 需要提供初始數值,用于區間為空的時候得到一個明確定義的結果
#include <iostream>   //std::cout
#include <functional> //std::minuc
#include <numeric>    //std::adjacent_differencetemplate <class InputIterator,class OutputIterator,class T>
T inner_product(InputIterator first1,InputIterator last1,InputIterator first2,T init){while (first1 != last1){init =init + (*first1) * (*first2);++first1;++first2;}return init;
}template <class InputIterator,class OutputIterator,class T,class BinaryOperation1,class BinaryOperation2>
T inner_product(InputIterator first1,InputIterator last1,InputIterator first2,T init,BinaryOperation1 binary_op1,BinaryOperation2 binary_op2){//以第一序列的元素個數為依據,將兩個序列都遍歷一遍while (first1 != last1){init = binary_op1(init,binary_op2(*first1,*first2));++first1;++first2;}return init;
}int myaccumulator(int x,int y){return x-y;}
int myproduct(int x,int y){return x+y;}int main(){int init = 100;int series1[] = {10,20,30};int series2[] = {1,2,3};std::cout << "using default inner_product" << std::endl;std::cout << std::inner_product(series1,series1+3,series2,init);
//    for (int i = 0; i < 7; ++i) {
//        std::cout << result[i] << ' ';
//    }std::cout << std::endl;std::cout << "using functional operations" << std::endl;std::cout << std::inner_product(series1,series1+3,series2,init,std::minus<int>(),std::divides<int>());
//    for (int i = 0; i < 7; ++i) {
//        std::cout << result[i] << ' ';
//    }std::cout << std::endl;std::cout << "using custom functions" << std::endl;std::cout << std::inner_product(series1,series1+3,series2,init, myaccumulator, myproduct);
//    for (int i = 0; i < 7; ++i) {
//        std::cout << result[i] << ' ';
//    }std::cout << std::endl;
//    using default inner_product
//    240 = 100 + (10*1) + (20*2) + (30*3)
//    using functional operations
//    70 = 100 - (10/1) - (20/2) - (30/3) 
//    using custom functions
//    34 = 100 - (10+1) - (20+2) - (30+3)
}

partial_sum

  • partial_sum用于計算局部總和,將*first賦值給*result,將*first和*(first+1)的數值的和賦值給*(result+1)
  • 可以轉化為質變算法
  • 函數返回 result + (last - first)
  • 和先前介紹的adjacent_difference互為逆運算

?

#include <iostream>   //std::cout
#include <functional> //std::minuc
#include <numeric>    //std::adjacent_differencetemplate <class InputIterator,class OutputIterator>
OutputIterator partial_sum(InputIterator first,InputIterator last,OutputIterator result){if (first != last){typename  std::iterator_traits<InputIterator>::value_type val = *first;*result = val;while (++first!=last){val = val + *first;*++result = val;}++result;}return result;
}template <class InputIterator,class OutputIterator,class BinaryOperation>
OutputIterator partial_sum(InputIterator first,InputIterator last,BinaryOperation binary_op,OutputIterator result){if (first != last){typename  std::iterator_traits<InputIterator>::value_type val = *first;*result = val;while (++first!=last){val = binary_op(val,*first);*++result = val;}++result;}return result;
}//int myaccumulator(int x,int y){return x-y;}
//int myproduct(int x,int y){return x+y;}int myop(int x,int y){return x+y+1;}int main(){
//    int init = 100;int series1[] = {1,2,3,4,5};int result[5];std::cout << "using default partial_sum" << std::endl;std::partial_sum(series1,series1+5,result);for (int i = 0; i < 5; ++i) {std::cout << result[i] << ' ';}std::cout << std::endl;std::cout << "using functional operation multiplies" << std::endl;std::partial_sum(series1,series1+5,result,std::multiplies<int>());for (int i = 0; i < 5; ++i) {std::cout << result[i] << ' ';}std::cout << std::endl;std::cout << "using custom functions" << std::endl;std::partial_sum(series1,series1+5, result,myop);for (int i = 0; i < 5; ++i) {std::cout << result[i] << ' ';}std::cout << std::endl;
//    using default partial_sum
//    1 3 6 10 15
//    using functional operation multiplies
//    1 2 6 24 120
//    using custom functions
//    1 4 8 13 19
}

Power

  • ?計算某數的n冪次方 即自己對自己進行某種運算到達n次
  • 運算類型可以由外界指定,如果指定為乘法那就是 乘冪
  • 目前使用pow替代
//版本1 乘冪
template <class T,class Integer>
inline T power(T x,Integer n){return power(x,n,std::multiplies<T>());
}//冪次方 指定為乘法運算,則當n >= 0 返回 x^n
//需要滿足結合律 但是不需要滿足交換律
template <class T,class Integer,class MonoidOperation>
T power(T x,Integer n,MonoidOperation op){if (n==0){return identity_element(op);} else{while((n&1)==0){n>>=1;x = op(x,x);}T result = x;n >> 1;while(n!=0){x = op(x,x);if ((n&1)!=0)result = op(result,x);n >>= 1;}return result;}
}

itoa

  • ?用于設定某個區間的內容,使其內的每一個元素從指定的value數值開始,呈現遞增的狀態
  • 質變算法
  • 在[first,last)區域內填入 value ,value+1,value+2
template <class ForwardIterator,class T>
void iota(ForwardIterator first,ForwardIterator last,T value){while(first != last){*first++ = value++;}
}

參考鏈接

  • accumulate - C++ Reference
  • adjacent_difference - C++ Reference
  • inner_product - C++ Reference
  • https://www.cplusplus.com/reference/numeric/partial_sum/?kw=partial_sum
  • pow - C++ Reference

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/446225.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/446225.shtml
英文地址,請注明出處:http://en.pswp.cn/news/446225.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

python官網網址是什么意思_大家都是怎么部署python網站的?

flaskgunicornnginx 作者&#xff1a;Python小白 鏈接&#xff1a;centos下通過gunicorn和nginx部署Flask項目 - Python小白的文章 - 知乎專欄 來源&#xff1a;知乎 著作權歸作者所有。商業轉載請聯系作者獲得授權&#xff0c;非商業轉載請注明出處。 之前用Flask寫了個解析Tu…

java回形數矩陣

題目 從鍵盤輸入一個整數&#xff08;1~20&#xff09; 則以該數字為矩陣的大小&#xff0c;把1,2,3…n*n 的數字按照順時針螺旋的形式填入其中。例如&#xff1a; 輸入數字2&#xff0c;則程序輸出&#xff1a; 1 2 4 3 輸入數字3&#xff0c;則程序輸出&#xff1a; 1 2 3 8…

STL源碼剖析 基本算法 equal | fill | iter_awap | lexicographical_compare | max | min | swap |mismatch

Equal 兩個序列在[first,last)區間內相等&#xff0c;equal()返回true。以第一個序列作為基準&#xff0c;如果第二序列元素多不予考慮&#xff0c;如果要保證兩個序列完全相等需要比較元素的個數 if(vec1.size() vec2.size() && equal(vec1.begin(),vec1.end(),vec2…

svm分類器訓練詳細步驟_「五分鐘機器學習」向量支持機SVM——學霸中的戰斗機...

大家好&#xff0c;我是愛講故事的某某某。 歡迎來到今天的【五分鐘機器學習】專欄內容 --《向量支持機SVM》 今天的內容將詳細介紹SVM這個算法的訓練過程以及他的主要優缺點&#xff0c;還沒有看過的小伙伴歡迎去補番&#xff1a;【五分鐘機器學習】向量支持機SVM——學霸中的…

java一維數組的復制

題目 使用簡單數組(1)創建一個名為ArrayTest的類&#xff0c;在main()方法中聲明array1和array2兩個變量&#xff0c;他們是int[]類型的數組。(2)使用大括號{}&#xff0c;把array1初始化為8個素數&#xff1a;2,3,5,7,11,13,17,19。(3)顯示array1的內容。(4)賦值array2變量等…

STL源碼剖析 數值算法 copy 算法

copy復制操作&#xff0c;其操作通過使用assignment operator 。針對使用trivial assignment operator的元素型別可以直接使用內存直接復制行為(使用C函數 memove或者memcpy)節約時間。還可以通過函數重載(function overloading)、型別特性(type traits)、偏特化(partial speci…

python輸入數字成數組_python – Numpy:將數值插入數組的最快方法,使得數組按順序排列...

假設我有一個數組my_array和一個奇異值my_val. (請注意,my_array始終排序). my_array np.array([1, 2, 3, 4, 5]) my_val 1.5 因為my_val是1.5,我想把它放在1和2之間,給我數組[1,1.5,2,3,4,5]. 我的問題是&#xff1a;當my_array任意增大時,生成有序輸出數組的最快方式(即以微…

java 一維數組的反轉

代碼 public class ReverseArray {public static void main(String[] args) {String[] str {"AA", "BB", "CC", "DD"};System.out.println(Arrays.toString(str));reverse1(str);System.out.println(Arrays.toString(str));reverse2…

STL源碼剖析 數值算法 copy_backward 算法

copy_backward 時間技巧和copy類似主要是將[first&#xff0c;last)區間范圍內的元素按照逆行方向復制到以result-1為起點&#xff0c;方向同樣是逆行的區間上返回的迭代器的類型是result - (last - first)copy_backward支持的類型必須是BidirectionalIterators &#xff0c;才…

java線性查找和二分查找

線性查找 package lesson.l7_array;/*** Illustration** author DengQing* version 1.0* datetime 2022/6/23 14:19* function 線性查找*/ public class LineSearch {public static void main(String[] args) {String[]str{"AA","BB","CC"};boo…

python開發web項目_Django2:Web項目開發入門筆記(20)

該樓層疑似違規已被系統折疊 隱藏此樓查看此樓 這一篇教程&#xff0c;我們一起來了解如何在CentOS系統中將Django2的Web項目部署到Nginx服務器。 CentOS系統雖然和Ubuntu系統都是Linux系統&#xff0c;但是環境搭建和部署過程還是有一些區別。 整個流程分為幾個部分&#xff1…

STL源碼剖析 Set相關算法 并集 set_union|交集 set_intersection|差集 set_difference |對稱差集 set_symmetric_difference

注意事項 四種相關算法&#xff1a;并集、交集、差集、對稱差集本章的四個算法要求元素不可以重復并且經過了排序底層接受STL的set/multiset容器作為輸入空間不接受底層為hash_set和hash_multiset兩種容器 并集 set_union s1 U s2考慮到s1 和 s2中每個元素都不唯一&#xff0…

python sqlserver 數據操作_python對Excel數據進行讀寫操作

python對Excel數據進行讀寫操作將學習到的基礎操作記錄在這里&#xff0c;便與復習查看1.python讀取Excel工作簿、工作表import xlrd # 讀取工作簿 wbxlrd.open_workbook(招生表.xls) # 讀取工作簿下所有的工作表 wswb.sheets() # 讀取工作簿下所有工作表名稱 wsnamewb.sheet_n…

Arrays數組工具類

介紹 代碼 package lesson.l8_arrays;import java.util.Arrays;/*** Illustration** author DengQing* version 1.0* datetime 2022/6/23 16:53* function Arrays數組工具類*/ public class ArraysUtil {public static void main(String[] args) {int[] arr1 new int[]{1, 12…

通過解析URL實現通過Wifi的用戶查找

使用鏈接 遇見數據倉庫|遇見工具|IP地址精確查詢|WIFI精確查詢|在線語音識別|夢幻藏寶閣估價|福利資源|自定義導航-met.redhttps://sina.lt/ 操作步驟 打開第一個鏈接&#xff0c;點擊高精度IP定位&#xff0c;然后點擊右上角&#xff0c;創建一個Key&#xff0c;隨便輸入一…

anaconda中怎么sh_【好工具】 深度學習煉丹,你怎么能少了這款工具!JupyterLab 遠程訪問指南...

歡迎來到【好工具】專欄&#xff0c;本次我們給介紹一款可以進行遠程深度學習煉丹的工具 JupyterLab 及其配置流程&#xff0c;幫助讀者在本地進行調試&#xff0c;Max 開發效率。作者 & 編輯 | Leong導言不知道讀者們有沒有發現&#xff0c;如果你用 Anaconda 中的 Notebo…

java 類和對象 屬性和行為 成員變量和局部變量

概念 使用 案例 public class PersonText {public static void main(String[] args) {Person person new Person();person.name "dq";person.age 11;person.eat("番茄炒蛋");} }class Person {/*** 姓名*/String name;/*** 年齡*/Integer age;/*** 方…

STL源碼剖析 數值算法 heap算法

算法 adjacent_findcountcount_iffindfind_iffind_endfor_eachgenerategenerate_nincludesmax_elementmergemin_elementpartitionremoveremoveremove_copyremove_ifremove_copy_ifreplacereplace_copyreplace_ifreplace_copy_ifreversereverse_copyrotaterotate_copysearchsea…

java 學生對象數組

題目 代碼 package lesson.l10_oop;/*** Illustration** author DengQing* version 1.0* datetime 2022/7/1 9:57* function*/ public class Student {int number;int state;int score;public static final int NUM 20;public static void main(String[] args) { // 對…

STL源碼剖析 lower_bound | upper_bound | binary_search

lower_bound 二分查找的一種版本&#xff0c;試圖在已經排序的區間內查找元素value&#xff0c;如果區間內存在和value數值相等的元素&#xff0c;便返回一個迭代器&#xff0c;指向其中的第一個元素。如果沒有數值相等的元素&#xff0c;會返回假設這個元素存在的前提下應該出…