Lambda Expressions vs Function Pointers - GeeksforGeeks

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

A Lambda expression is also called an anonymous function. It is an expression contained within the main function and helps while passing a ... Skiptocontent CoursesForWorkingProfessionalsLIVEDSALiveClassesSystemDesignJavaBackendDevelopmentFullStackLIVEExploreMoreSelf-PacedDSA-SelfPacedSDETheoryMust-DoCodingQuestionsExploreMoreForStudentsLIVECompetitiveProgrammingDataStructureswithC++DataScienceExploreMoreSelf-PacedDSA-SelfPacedCIPJAVA/Python/C++ExploreMoreSchoolCoursesSchoolGuidePythonProgrammingLearnToMakeAppsExploremoreAllCoursesTutorialsAlgorithmsAnalysisofAlgorithmsAsymptoticAnalysisWorst,AverageandBestCasesAsymptoticNotationsLittleoandlittleomeganotationsLowerandUpperBoundTheoryAnalysisofLoopsSolvingRecurrencesAmortizedAnalysisWhatdoes'SpaceComplexity'mean?Pseudo-polynomialAlgorithmsPolynomialTimeApproximationSchemeATimeComplexityQuestionSearchingAlgorithmsSortingAlgorithmsGraphAlgorithmsPatternSearchingGeometricAlgorithmsMathematicalBitwiseAlgorithmsRandomizedAlgorithmsGreedyAlgorithmsDynamicProgrammingDivideandConquerBacktrackingBranchandBoundAllAlgorithmsDataStructuresArraysLinkedListStackQueueBinaryTreeBinarySearchTreeHeapHashingGraphAdvancedDataStructureMatrixStringsAllDataStructuresInterviewCornerCompanyPreparationTopTopicsPracticeCompanyQuestionsInterviewExperiencesExperiencedInterviewsInternshipInterviewsCompetititveProgrammingDesignPatternsSystemDesignTutorialMultipleChoiceQuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGoLanguageHTMLCSSKotlinML&DataScienceMachineLearningDataScienceCSSubjectsMathematicsOperatingSystemDBMSComputerNetworksComputerOrganizationandArchitectureTheoryofComputationCompilerDesignDigitalLogicSoftwareEngineeringGATEGATEComputerScienceNotesLastMinuteNotesGATECSSolvedPapersGATECSOriginalPapersandOfficialKeysGATE2021DatesGATECS2021SyllabusImportantTopicsforGATECSWebTechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftwareDesignsSoftwareDesignPatternsSystemDesignTutorialSchoolLearningSchoolProgrammingMathematicsNumberSystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMathsNotes(Class8-12)Class8NotesClass9NotesClass10NotesClass11NotesClass12NotesNCERTSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionRDSharmaSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionPhysicsNotes(Class8-11)Class8NotesClass9NotesClass10NotesClass11NotesChemistryNotesClass8NotesClass9NotesClass10NotesCSExams/PSUsISROISROCSOriginalPapersandOfficialKeysISROCSSolvedPapersISROCSSyllabusforScientist/EngineerExamUGCNETUGCNETCSNotesPaperIIUGCNETCSNotesPaperIIIUGCNETCSSolvedPapersStudentCampusAmbassadorProgramSchoolAmbassadorProgramProjectGeekoftheMonthCampusGeekoftheMonthPlacementCourseCompetititveProgrammingTestimonialsStudentChapterGeekontheTopInternshipCareersJobsApplyforJobsPostaJobHirewithUsKnowaboutJobathonJobathonPracticeAllDSAProblemsProblemoftheDayInterviewSeries:WeeklyContestsBi-WizardCoding:SchoolContestsContestsandEventsPracticeSDESheetCuratedDSAListsTop50ArrayProblemsTop50StringProblemsTop50TreeProblemsTop50GraphProblemsTop50DPProblems ComewritearticlesforusandgetfeaturedLearnandcodewiththebestindustryexpertsGetaccesstoad-freecontent,doubtassistanceandmore!ComeandfindyourdreamjobwithusGeeksDigestQuizzesGeeksCampusGblogArticlesIDECampusMantriHomeSavedVideosCoursesGBlogPuzzlesWhat'sNew? ChangeLanguage DataStructuresAlgorithmsInterviewPreparationTopic-wisePracticeC++JavaPythonCompetitiveProgrammingMachineLearningHTMLSDESheetPuzzlesGFGSchoolProjects RelatedArticles ▲RelatedArticlesVectorinC++STLArraysinC/C++std::sort()inC++STLInitializeavectorinC++(7differentways)MapinC++StandardTemplateLibrary(STL)TheC++StandardTemplateLibrary(STL)BitwiseOperatorsinC/C++InheritanceinC++ObjectOrientedProgramminginC++C++ClassesandObjectsConvertingStringstoNumbersinC/C++C++DataTypesVirtualFunctioninC++ConstructorsinC++SetinC++StandardTemplateLibrary(STL)MultidimensionalArraysinC/C++vectorerase()andclear()inC++LeftShiftandRightShiftOperatorsinC/C++SocketProgramminginC/C++rand()andsrand()inC/C++CopyConstructorinC++unordered_mapinC++STLStackinC++STLTemplatesinC++withExamples2DVectorInC++WithUserDefinedSizeSubstringinC++getline(string)inC++DifferentMethodstoReverseaStringinC++OperatorOverloadinginC++PriorityQueueinC++StandardTemplateLibrary(STL)VectorinC++STLArraysinC/C++std::sort()inC++STLInitializeavectorinC++(7differentways)MapinC++StandardTemplateLibrary(STL)TheC++StandardTemplateLibrary(STL)BitwiseOperatorsinC/C++InheritanceinC++ObjectOrientedProgramminginC++C++ClassesandObjectsConvertingStringstoNumbersinC/C++C++DataTypesVirtualFunctioninC++ConstructorsinC++SetinC++StandardTemplateLibrary(STL)MultidimensionalArraysinC/C++vectorerase()andclear()inC++LeftShiftandRightShiftOperatorsinC/C++SocketProgramminginC/C++rand()andsrand()inC/C++CopyConstructorinC++unordered_mapinC++STLStackinC++STLTemplatesinC++withExamples2DVectorInC++WithUserDefinedSizeSubstringinC++getline(string)inC++DifferentMethodstoReverseaStringinC++OperatorOverloadinginC++PriorityQueueinC++StandardTemplateLibrary(STL)LambdaExpressionsvsFunctionPointersViewDiscussion ImproveArticle SaveArticle LikeArticle DifficultyLevel: MediumLastUpdated: 01Oct,2021FunctionPointer:Afunctionpointer,orasubroutinepointer,oraprocedurepointer,isapointerthatpointstoafunction.Insimplewords,itisapointertothelocationinsidethetextsection.Itstorestheaddressofafunctionandisusedforpassingabehaviorasaparametertoanotherfunction.Forinstance,ifsomeonewantstosortacontainerlikeavector,orlists,andusestheSTLsort(),butdoesn’twishtosortitinascendingorder,whichisthedefaultparameter,inthatcase,passabehaviortothesortfunction,whichisactuallythefunctionpointer,andgethisdatasorted.Program1:BelowistheC++programtoimplementtheaboveconcept:C++//C++programtoimplementtheabove//concepts#includeusingnamespacestd; //Descendingordersortingfunctionintdescending(intx,inty){    returnx>y;} //Absolutevaluesortingfunctionintabsolute(intx,inty){    returnabs(x)>abs(y);} //DriverCodeintmain(){    //Storesintegersinthevector    vectorvect={2,8,-5,-9,                         0,12,5};     cout<usingnamespacestd; //Functionhavingnoparametervoidfun(){    cout<{    //Body};ConstructsofaLambdaExpression: []:capturelist():parameter->:arrow.:returntype{}:functionbodyProgram3:Belowistheprogramillustratinghowlambdaexpressionscanbeusedforsortingindescendingorderaswellaswithabsolutevalues.C++//C++programtoillustratethe//aboveconcept#includeusingnamespacestd; //DriverCodeintmain(){    vectorvect{-1,-6,4,2,0,                      6,3,9,-5};     cout<b;         });     for(autoi:vect)        cout<abs(b);         });     for(autoi:vect)        cout<usingnamespacestd; //DriverCodeintmain(){    intx=0,a=5,b=4;     //Inthebelowlambdaexpression,    //everythingiscapturedbyvalue,    //andonlyxbyreference    autofun=[=,&x](intx){         //Ifonetriestomanipulate        //thevalueofareadonly        //variable,thenitcauses        //acompilationerror.        x++;         //cisanewvariableunder        //thefunexpressionwhich        //sumsupaandb        intc=a+b;         cout<



請為這篇文章評分?