標準庫函數對象,eg.equal_to<Type>
適配器eg. bind2nd(less_equal<int>(), 10)
not1(bind2nd(less_equal<int>(),10))
//函數對象的函數適配器#include"head.h"int main(){//綁定器binder:bind1st,bind2nd;綁定一個現成的實參到二元函數對象函數第一個或第二個參數,使之變成一元函數int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};std::vector<int> vec(a, a + 10); std::cout << count_if(vec.begin(), vec.end(), std::bind2nd(std::less_equal<int>(), 7)) << std::endl;//less_equal<Type> 不支援std::string類型//求反器negator:not1,not2;將一元函數對象或二元函數對象的真值求反//求反與綁定的嵌套使用std::cout << count_if(vec.begin(), vec.end(), not1(std::bind2nd(std::less_equal<int>(), 7))) << std::endl;}
pe14_37.cpp,
38,39都被相容了
(mark) c題的意思。要求
//使用標準庫函數對象和函數適配器,定義一個對象用於:(a)、(b)、(c)//不是要一個對象完成三個功能(太恐怖了,重載。),是三個小題吧~。#include"head.h"int main(){ //a)尋找大於1024的所有值 int a[] = {10000, 2, 3, 4, 5, 6, 1024, 8, 9, 1025}; std::vector<int> vec(a, a + 10); //所謂定義一個對象,greater就是--函數對象 std::cout << count_if(vec.begin(), vec.end(), std::bind2nd(std::greater<int>(), 1024)) << std::endl; std::cout << count_if(vec.begin(), vec.end(), std::bind2nd(std::greater_equal<int>(), 1025)) << std::endl; std::cout << count_if(vec.begin(), vec.end(), std::not1(std::bind2nd(std::less_equal<int>(), 1024))) << std::endl; std::cout << count_if(vec.begin(), vec.end(), std::not1(std::bind2nd(std::less<int>(), 1025))) << std::endl; //b)尋找不等於pooh的所有字串 //find_if()找出來列印。count_if()計算出來數量。 std::vector<std::string> svec(3, "world"); svec.push_back("hello"); svec.push_back("pooh"); std::string compare = "pooh"; //方法一,bind2nd綁定not_equal_to,用count_if計數 std::cout << "the number of strings not sames to " << compare << ": " <<count_if(svec.begin(), svec.end(), std::bind2nd(std::not_equal_to<std::string>(), compare)) << std::endl; //方法二:用bind2nd綁定equal_to和要尋找string對象"pooh",外層not1, //這裡只能not1吧,這裡是標準庫演算法傳遞一個對象進來求bool值,只能是調用一元函數對象 std::cout << "the number of strings sames to " << compare << ": " << count_if(svec.begin(), svec.end(), std::not1(std::bind2nd(std::equal_to<std::string>(), compare))) << std::endl;//not1求反,或者用logical_not<Type> //c)將所有值乘以2 //我該用什麼演算法遍曆,用count_if過一遍,再用multiplies<Type>乘以2。No~!!!! //按理說都是傳遞參數進行指定操作啊,標準庫演算法只管傳實參,裡邊用哪個操作他就別管我了,multiplies也沒說不允許傳遞 //錯誤:因為傳進去即使能做操作,可能是給副本做的操作,又不能返回引用和副本來改原值。。。find_if更沒戲,是尋找位置返回迭代器的 //現在能想到的,只有需要傳遞一個函數的標準庫演算法,實際上沒接觸幾個~。做判斷用的返回bool類型的又無效, int multi = 2; std::cout << count_if(vec.begin(), vec.end(), std::bind2nd(std::multiplies<int>(), multi)) << std::endl; //我更相信他要的是這個意思(可能需要個重載,來搞定doubl之類的。): //類似於 std::plus<int> intAdd;定義一個對象,沒要求非要把一個容器裡邊的元素乘以2,是誰調用它誰乘以2(a、b兩題明顯是對整個容器) //std::bind2nd(std::multiplies<int>, multi) intMulti2;//可是這個聲明不出來 //列印驗證 for(std::vector<int>::iterator iter = vec.begin(); iter != vec.end(); iter++){ std::cout << *iter << "\t"; } }