The C++ Programming Language最全版.ppt

  1. 1、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。。
  2. 2、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载
  3. 3、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
The C++ Programming Language最全版.ppt

Design a generic algorithm (cont.) Function Objects Adaptor – Brings more flexibility Binder adaptor – bind the parameter of function object to certain value, thus transform the binary function object to unary function object bind1st(lessint, 10) bind2nd(lessint, 10) Negator adaptor – negate the return value of function object not1( bind2nd(lessint, 10) ) – unary not2(lessint) – binary C++ 11? * yrty Design a generic algorithm (cont.) Second solution: Using function objects to replace pointer to function Using generic find_if() to replace container-related addressing vectorint filter_ver2(const vectorint vec, int threshold, lessint lt) { vectorint nvec; vectorint::const_iterator it = vec.begin(); while ((it = find_if(it, vec.end(), bind2nd(lt, threshold))) != vec.end()) { nvec.push_back(*it); it++; } return nvec; } * yrty Design a generic algorithm (cont.) Final solution: Make it more generic, independent with container and type templatetypename InputIter, typename OutputIter, typename ElemType, typename Comp OutputIter filter(InputIter first, InputIter last, OutputIter at, const ElemType thres, Comp pred) { while ((first = find_if( first, last, bind2nd( pred, thres ) )) != last) { *at++ = *first++; } return at; } The filter() is a complete generic algorithm now! * yrty Supplement * yrty Iterator Inserters Imaging the calling of previous filter() int main { int iSize = 8; int ia[ iSize ] = {12, 8, 4, 13, 65, 3, 0, 20}; vectorint ivec(ia, ia + iSize); int ia2[ iSize ]; vectorint ivec2; filter(ia, ia+iSize, ia2, 10, lessint()); filter(ivec.begin(), ivec.end(), ivec2.begin(), 10, greaterint()); } Ok, because the array is assigned space Will cause runtime error, because iterator will point to an illegal position Does this mean we always need to prepare a container of enough size? * yrty Ite

文档评论(0)

liuxiaoyu92 + 关注
实名认证
内容提供者

该用户很懒,什么也没介绍

1亿VIP精品文档

相关文档