C++for_each| bind1st | ptr_fun | std::function的用法

c++ for_each 用法_小鍵233-CSDN博客

傳入參數

  • 要傳入參數給global function ,需要使用 ptr_fun() 這個 function adapter 將global function 轉成function object , 然后再用bind2nd() 將參數bind成一個function object。(這句話好拗口)
void fun(int i, const char* str)
{cout<<str<<i<<endl;
}int main()
{int a[] = { 1, 2, 3, 4};vector<int> v(a, a+sizeof(a)/sizeof(int));for_each(v.begin(), v.end(), bind2nd(ptr_fun(fun), "Element:"));
}
#include <iostream>
#include <vector>template<class T>
struct plus2{void operator()(T& x){x += 2;}
};//template <class T>
void plus3_fun(int& x){x += 3;
//    std::cout << x << " ";
}void fun(int i,const char* str){std::cout << str << "->" << i << std::endl;
}int main(){
//    int ia[] = {22,30,20,34,45,64,34,56,75,34};
//    std::vector<int>iv(ia,ia+(sizeof (ia) / sizeof (int)));
//    for (int i : iv) {
//        std::cout << i << ' ';
//    }
//    std::cout << std::endl;
//    std::cout << iv.size() << ' ';
//    std::cout << std::endl;
//std::for_each(iv.begin(),iv.end(),plus2<int>());
//    std::for_each(iv.begin(),iv.end(), std::bind2nd(std::ptr_fun(fun),"Hello world"));
//    for (int i : iv) {
//        std::cout << i << ' ';
//    }int ia[] = {1,2,100,200};std::vector<int>arr(ia,ia+(sizeof (ia)/sizeof (int)));//移除所有小于100的元素//bind2nd(判斷條件,標準)  判斷條件 標準//bind1nd(判斷條件,標準)  標準 判斷條件/** std::bind1nd(std::less<int>(),100))   100 < x* std::bind2nd(std::less<int>(),100))   x < 100*/
//    arr.erase(std::remove_if(arr.begin(),arr.end(),std::bind2nd(std::less<int>(),100)),arr.end()); //100 200
//    arr.erase(std::remove_if(arr.begin(),arr.end(),std::bind1st(std::greater<int>(),100)),arr.end());//    arr.erase(std::remove_if(arr.begin(),arr.end(),std::bind2nd(std::greater<int>(),100)),arr.end());
//    arr.erase(std::remove_if(arr.begin(),arr.end(),std::bind1st(std::less<int>(),100)),arr.end()); //1 2 100//刪除小于等于100的元素arr.erase(std::remove_if(arr.begin(),arr.end(),std::not1(std::bind2nd(std::greater<int>(),100))),arr.end());for(auto i : arr){std::cout << i << " ";}
}

ptr_fun

  • C++11棄用 被更通用的std::function 和 std::ref替代
#include <iostream>
#include <vector>
#include <functional>
#include <algorithm>bool isvowel(char c){return std::string("aeiouAEIOU").find(c) != std::string::npos;
}int main(){std::string s = "Hello world!";std::copy_if(s.begin(),s.end(),std::ostreambuf_iterator<char>(std::cout),std::not1(std::ptr_fun(isvowel)));
}//Hll wrld!

std::function函數

  • std::function - cppreference.com?
#include <iostream>
#include <vector>
#include <functional>
#include <algorithm>struct Foo{Foo(int num):num_(num){};void print_add(int i)const {std::cout << num_ + i << std::endl;}int num_;
};
void print_num(int i){std::cout << i << '\n';
}
struct print_Num{void operator()(int i){std::cout << i << '\n';}
};int main(){//store a free functionstd::function<void(int)>f_display = print_num;f_display(-9);//strore a lambdastd::function<void()> f_display_42 = [](){ print_num(43);};f_display_42();//store the result of a call to std::bindstd::function<void()>f_display_31337 = std::bind(print_num,31337);f_display_31337();//store a call to a member functionstd::function<void(const Foo&,int)>f_add_display = &Foo::print_add;const Foo foo(300000);f_add_display(foo,1);//store a call to a member function and objectusing std::placeholders::_1;std::function<void(int)>f_add_display2 = std::bind(&Foo::print_add,foo,_1);f_add_display2(2);//store a call to a member function and object ptrstd::function<void(int)>f_add_display3 = std::bind(&Foo::print_add,&foo,_1);f_add_display3(3);//store a call to a function objectstd::function<void(int)>f_display_obj = print_Num();f_display_obj(18);
}

參考鏈接

  • bind1st bind2nd的使用_simahao的專欄-CSDN博客_bind2nd
  • C++ STL std::ptr_fun() 函數說明 - 簡書
  • C++中string::npos的一些用法總結_竭盡全力的專欄-CSDN博客

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

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

相關文章

java三個柱子漢諾塔問題

題目 移動盤子&#xff0c;每一次只能移動一個&#xff0c;小盤子在大盤子上。 打印1 from A to B過程 注意 1&#xff09;盤子編號的變化和輔助柱子的變化 2&#xff09;當盤子編號為1時&#xff0c;結束遞歸&#xff0c;此時移動結束 代碼 package p2;/*** Illustratio…

python遍歷txt每一行_python – 計算(和寫入)文本文件中每一行的...

第一次在堆棧中發布 – 總是發現以前的問題足以解決我的問題&#xff01;我遇到的主要問題是邏輯……即使是偽代碼答案也會很棒. 我正在使用python從文本文件的每一行讀取數據,格式如下&#xff1a; This is a tweet captured from the twitter api #hashtag http://url.com/si…

java楊輝三角形

題目 代碼1 public class YangHuiTriangle {public static void main(String[] args) {print(10);}public static void print(int num) {int[][] arr new int[num][];for (int i 0; i < num; i) { // 第一行有 1 個元素, 第 n 行有 n 個元素arr[i] new int[i…

python子類繼承父類屬性實例_python – 從子類內的父類訪問屬性

在類定義期間,沒有任何繼承的屬性可用&#xff1a; >>> class Super(object): class_attribute None def instance_method(self): pass >>> class Sub(Super): foo class_attribute Traceback (most recent call last): File "", line 1, in cl…

STL源碼剖析 算法開篇

STL源碼剖析 算法章節 算法總覽_CHYabc123456hh的博客-CSDN博客 質變算法 質變算法 - 會改變操作對象的數值&#xff0c;比如互換、替換、填寫、刪除、排列組合、分隔、隨機重排、排序等 #include <iostream> #include <vector>int main(){int ia[] {22,30,20,34…

java 隨機數一維數組

題目1 創建一個長度為6的int型數組&#xff0c;要求數組元素的值都在1-30之間&#xff0c;且是隨機賦值。同時&#xff0c;要求元素的值各不相同 代碼1 public class ArrayTest2 {public static void main(String[] args) {generateArray(6);}public static void generateAr…

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 Bin…

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…