C++ Array of Function Pointers: Practical Overview for Beginners

文章推薦指數: 80 %
投票人數:10人

You can declare an array of function pointers in C++ using std::vector<:function>> notation, where you should also specify the template ... Signin Home Css C++ HTML MYSQL PHP JavaScript Programming Errors&Warnings ComputerTips Signin Welcome!Logintoyouraccount yourusername yourpassword Forgotyourpassword? Passwordrecovery Recoveryourpassword youremail Search Thursday,June23,2022 Signin/JoinAboutUs PrivacyPolicy CookiePolicy ContactUs Signin Welcome!Logintoyouraccount yourusername yourpassword Forgotyourpassword?Gethelp Passwordrecovery Recoveryourpassword youremail Apasswordwillbee-mailedtoyou. Home Css C++ HTML MYSQL PHP JavaScript Programming Errors&Warnings ComputerTips PositionIsEverything HomeC++C++ArrayofFunctionPointers:OnlyIntroductionYouWillNeed C++ Facebook Twitter Pinterest WhatsApp C++arrayoffunctionpointerscanbedeclaredusingseveraltechniquesinC++,butwewillmostlyfocusonstd::functionclasstemplateandlambdaexpressions.Generally,functionpointersareoftenthoughtofasrawpointersthatpointtothefunctionobjects,butC++providesamoreabstractconstructwiththestd::functionclass. Additionally,it’srathereasierforbeginnerstograspthestd::function-basedsyntaxthanrawC-stylefunctionpointerdeclarations.O,youcanjustkeepreadingtolearnmoreabouttheusageoffunctionobjectsinC++. ContentsHowToDeclareanArrayofFunctionPointersinC++–Code–ProgramOutput:CreateC++ArrayofFunctionPointerswithLambdaExpressions–Code–ProgramOutput:InitializeC++ArrayofFunctionPointerswithLambdaExpressions–Code–ProgramOutput:UtilizeC++MapofFunctionPointersWithSTLAlgorithms–Code–ProgramOutput:HowToDeclareArrayofPointersinC++?–CodeDeclareArrayofPointersUsingNewOperator–CodeFinalThoughts HowToDeclareanArrayofFunctionPointersinC++ YoucandeclareanarrayoffunctionpointersinC++usingstd::vector<:function>>notation,whereyoushouldalsospecifythetemplateparametersforthestd::functionasneeded.Inthiscase,weinsertedint(int,int)typetodenotethefunctionsthataccepttwointargumentsandalsohaveanintreturntype. Notethatthefunctionsadd()andsubtract()aredefinedwiththesameparameters.Consequently,wecanaddthesefunctionstothevectorofstd::function-susingemplace_back()method. Eventhoughelementsofthisvectorrepresentabstractcallableobjects,wewillrefertothemasfunctionpointers.Eachfunctionpointercanbeaccessedusingtheregularnotationtoinvokethecorrespondingfunctionroutines.Wedemonstrateasimplerange-basedforloopiterationthroughthisvectorinthefollowingcodesnippet. Bearinmindthatthestd::functionhasbeenavailablesincetheC++11version. –Code #include #include #include usingstd::cout; usingstd::vector; usingstd::endl; usingstd::function; intadd(inti,intk){ returni+k; } intsubtract(inti,intk){ returni–k; } intmain(){ vector<:function>>ops; ops.emplace_back(add); ops.emplace_back(subtract);constintinput2=13; constintinput1=123; for(constauto&op:ops){ cout< #include #include usingstd::cout; usingstd::vector; usingstd::endl; usingstd::function; intmain(){ autoadd=[](inti,intk){returni+k;}; autosubtract=[](inti,intk){returni–k;}; automultiply=[](inti,intk){returni*k;}; autodivide=[](inti,intk){returni/k;}; autodivide_f=[](doublei,doublek){returni/k;}; vector<:function>>ops; ops.emplace_back(add); ops.emplace_back(subtract); ops.emplace_back(multiply); ops.emplace_back(divide); ops.emplace_back(divide_f); constintinput2=13; constintinput1=123; for(constauto&op:ops){ cout< #include #include #include #include usingstd::cout; usingstd::vector; usingstd::string; usingstd::endl; usingstd::function; intmain(){ constintinput2=13; constintinput1=123; vector<:function>>ops2{ [](inti,intk){returni+k;}, [](inti,intk){returni–k;}, [](inti,intk){returni*k;}, [](inti,intk){returni/k;}}; for(constauto&op:ops){ cout< #include #include #include #include usingstd::cout; usingstd::vector; usingstd::string; usingstd::endl; usingstd::function; usingstd::map; intmain(){ vectordata_vec{1,2,3,4,5,6, 20,21,22,23, 70,80,90,100}; map>ops3{ {“<10”,[](inti){returni<10;}}, {“>10”,[](inti){returni>10;}}, {“>50”,[](inti){returni>50;}}}; vector<:pair>>stats; stats.reserve(ops3.size()); for(constauto&op:ops3){ stats.emplace_back(op.first,std::count_if(data_vec.begin(),data_vec.end(),op.second)); } for(constauto&i:stats){ cout<10:8 >50:4 HowToDeclareArrayofPointersinC++? YoucandeclareanarrayofpointersinC++usingthestd::vectorcontainer.Sincethestd::vectorcanstoregenerictypesasitselements,anyrawpointercanbestoredinit.Thefollowingexampledemonstratesthebasicusagewhiledeclaringvectorsofint*anddouble*pointers,respectively. Noticethatallofthestatementsusetheconstructortoinitializethegivennumberofelementsinthevector,andsomeexplicitlyspecifynullptrasthevalueinitializer. –Code #include #include usingstd::cout; usingstd::vector; usingstd::endl; intmain(){ vectorvec1(10,nullptr); vectorvec3(10); vectorvec2(10,nullptr); return0; } DeclareArrayofPointersUsingNewOperator Additionally,youcandeclareandallocateanarrayofpointersusingthenewoperator.Thismethodusesthearraybracketsnotationtotakethesizeoftheresultingvector.Atthesametime,thetypeofpointersisspecifiedjustbeforetheopeningbracket. Thenextcodesnippetshowshowtodeclareanarrayofintpointerswiththearbitrarysizeof10.Remembertodeallocatedynamicmemoryregionsusingthedeleteoperator. –Code #include #include usingstd::cout; usingstd::vector; usingstd::endl; intmain(){ constintSIZE=10; int*vec_ptr=newint[SIZE]; for(inti=0;i>notation FunctionobjectscanbestoredinmostSTLcontainerse.g.,std::map Coveredtopicswillhelpyoubetterunderstandthecommonpatternsthatutilizefunctionobjectsinreal-worldC++projects.Meanwhile,keepaneyeonourupcomingarticlestoexploremorefascinatingpowersoftheC++language. 5/5-(13votes) AuthorRecentPostsPositionisEverythingPositionIsEverything:YourGo-ToResourceforLearn&Build:CSS,JavaScript,HTML,PHP,C++andMYSQL.LatestpostsbyPositionisEverything(seeall) ThermalPasteAlternative:UnconventionalWaysToUseHouseholdItems-June13,2022 VirtualMachineGaming:TheUniqueFutureofGamingandStreaming-June13,2022 3000mhzvs3200mhz:WhatAretheMostSignificantDifferences?-June13,2022 RELATEDARTICLESMOREFROMAUTHOR C++ C++StringTrim:HowToRemoveWhitespacesEffectively C++ C++PassArraybyReference–PracticalIntroductionforC++Newbies C++ C++SplitStringRoutine:PracticalOverviewofDifferentSolutions C++ C++WhileLoop–OverviewofLoopStatementsforC++Newbies C++ C++Inheritance–OverviewofBasicInheritanceTypesforNewbies C++ C++Polymorphism–APracticalIntroductionforC++Beginners LEAVEAREPLYCancelreply Pleaseenteryourcomment! Pleaseenteryournamehere Youhaveenteredanincorrectemailaddress! Pleaseenteryouremailaddresshere Savemyname,email,andwebsiteinthisbrowserforthenexttimeIcomment. Δ C++ C++StringTrim:HowToRemoveWhitespacesEffectivelyC++PositionisEverything-March2,20220 C++VectorInitialization:PracticalOverviewFromAllAnglesC++PositionisEverything-January29,20220 C++Inheritance–OverviewofBasicInheritanceTypesforNewbiesC++PositionisEverything-February21,20220 C++Matrix:LearnMatrixandItsConceptsinC++WithExpertsC++PositionisEverything-November12,20210 Loadmore reportthisad PositionIsEverythingprovidesthereaderswithCodingandComputingTips&Tutorials,TechnologyNews,Hardware&SoftwareReviews.Learn&Build:CSS,JavaScript,HTML,PHP,C++andMYSQL.Contactus:[email protected] AboutUs PrivacyPolicy CookiePolicy ContactUs SiteMap ©NewspaperWordPressThemebyTagDiv xx



請為這篇文章評分?