├── 1.1 Hello World.cpp ├── 1.Ex1 BasicMaths.cpp ├── 1.Ex4 BugFree Ex3.cpp ├── 10.1 SimplePisceanClassHeirarchy.cpp ├── 10.10 MultipleInheritance_Platypus.cpp ├── 10.2 Fish_With_protected.cpp ├── 10.3 Fish_WithBaseClassInstantiation.cpp ├── 10.4 DerivedClassOverridingMethod.cpp ├── 10.5 InvokingBaseMethods_InSpiteOverride.cpp ├── 10.6 MethodHiding.cpp ├── 10.6 Protected_SuperCar.cpp ├── 10.7 SequenceConstructionDestruction.cpp ├── 10.8 PvtInheritanceCarMotor.cpp ├── 10.9 ProtectedInheritance ├── 10.9 ProtectedInheritance.cpp ├── 10.Ex1 PlatypusConstructorOrder.cpp ├── 11.1 InvokingSwimUsingFishPtr.cpp ├── 11.2 FishSwim_VirtualMethod.cpp ├── 11.3 WithoutVirtualDestructors.cpp ├── 11.4 VirtualDestructors.cpp ├── 11.5 SizeofBaseClassWithVirtualFunctions.cpp ├── 11.6 FishABC.cpp ├── 11.7 MultipleInheritance_Platypus.cpp ├── 11.8 VirtualInheritance_Platypus.cpp ├── 11.9 VirtualCopyConstructors.cpp ├── 11.Ex3.cpp ├── 11.Quiz1.cpp ├── 12.1 Date_PrefixOperatorsIncDec.cpp ├── 12.10 ArraySubscriptOperator_MyString.cpp ├── 12.11 FunctionObjects_Functors_Operator().cpp ├── 12.12 MoveConstructorAssignmentOperator.cpp ├── 12.13 UDLtoKelvin.cpp ├── 12.2 OperatorConstCharPtr.cpp ├── 12.3 UniquePtr.cpp ├── 12.4 BinaryAdditionSubtractionOperator.cpp ├── 12.5 AddSubAssignment.cpp ├── 12.6 Equality_Inequality_Comparison.cpp ├── 12.7 ComparisonLessThanGreaterThanEqualTo.cpp ├── 12.8 SpaceshipCompareDates.cpp ├── 12.9 CopyAssignmentOperator.cpp ├── 13.1 dynamic_cast_Fish.cpp ├── 13.Ex2.cpp ├── 14.1 MacroConstants.cpp ├── 14.2 MacroFunctions.cpp ├── 14.3 TemplateFunctionGetMax.cpp ├── 14.4 HoldsPairWithMain.cpp ├── 14.5 TemplateSpecialization.cpp ├── 14.6 StaticWithinTemplate.cpp ├── 14.7 VariableTemplatesSum.cpp ├── 14.8 Tuple.cpp ├── 14.9 StaticAssert.cpp ├── 14.Ex6 DisplayVariadicTemp.cpp ├── 15.1 ContainerIteratorRelationship.cpp ├── 16.1 STLStringInstantiationCopy.cpp ├── 16.2 AccessingCharElements.cpp ├── 16.3 ConcatenateAdditionAssignmentAppend.cpp ├── 16.4 StringFind.cpp ├── 16.5 StringTruncate.cpp ├── 16.6 StringReverse.cpp ├── 16.7 StringCaseConversion.cpp ├── 16.8 StringLiteralsCPP14.cpp ├── 16.9 StringView.cpp ├── 16.Ex1 IsPalindrom.cpp ├── 16.Ex2 NumVowels.cpp ├── 16.Ex3 AlternateCharUC.cpp ├── 16.Ex4 InsertSpacesInStr.cpp ├── 16.Ex5 FindCharA.cpp ├── 17.1 InstantiatingStdVector.cpp ├── 17.2 InsertingPushBack.cpp ├── 17.3 VectorInsert.cpp ├── 17.4 VectorElementAccessArray.cpp ├── 17.5 VectorPointerSemantics.cpp ├── 17.6 VectorPopBack.cpp ├── 17.7 SizeCapacity.cpp ├── 17.8 DequeInsertionsDeletions.cpp ├── 17.Ex1 QueryVector.cpp ├── 17.Ex3 VectorPackageDimensions.cpp ├── 17.Ex4 DequeListInit.cpp ├── 18.1 InstantiatingList.cpp ├── 18.2 InsertingFrontEnd.cpp ├── 18.3 ListInsert.cpp ├── 18.4 ListErase.cpp ├── 18.5 ListReverse.cpp ├── 18.6 ListSort.cpp ├── 18.7 SortContactsList.cpp ├── 18.8 ForwardList.cpp ├── 18.Ex3 InsertVecInList.cpp ├── 18.Ex4 ListStrings.cpp ├── 19.1 InstantiatingSetMSet.cpp ├── 19.2 InsertSetMSet.cpp ├── 19.3 SetFind.cpp ├── 19.4 MSetErase.cpp ├── 19.5 SetContactsList.cpp ├── 19.6 UnorderedSet.cpp ├── 19.Ex1 ContactsSortedByNums.cpp ├── 19.Ex2 WordAndMeaning.cpp ├── 19.Ex3 SetMSetCompare.cpp ├── 2.1 HelloWorldAnalysis.cpp ├── 2.2 UsingNamespaceDecl.cpp ├── 2.3 UsingRestricted.cpp ├── 2.4 FirstFunction_Demo_cout.cpp ├── 2.5 FunctionValueReturnedFromMain.cpp ├── 2.6 Anatomy_BasicIO.cpp ├── 2.Ex2.cpp ├── 2.Ex3.cpp ├── 20.1 InstantiatingMapMultimap.cpp ├── 20.2 InsertingElements.cpp ├── 20.3 MapFind.cpp ├── 20.4 MapErase.cpp ├── 20.5 MultiMapWithPredicate.cpp ├── 20.6 unordered_map_sample.cpp ├── 21.1 FunctionObjects.cpp ├── 21.2 StatefulFunctionObject.cpp ├── 21.3 21.4 UsingUnaryPredicate.cpp ├── 21.5 BinaryFunctionMultiplyRanges.cpp ├── 21.6 21.7 BinarySortPredicate.cpp ├── 21.8 LambdaDisplayContainerForEach.cpp ├── 21.Ex1 DoubleElement.cpp ├── 21.Ex2 DoubleKeepCount.cpp ├── 21.Ex3 BinaryPredSort.cpp ├── 22.1 LambdaDisplayElements.cpp ├── 22.2 LambdaFindIfEvenNumbers.cpp ├── 22.3 LambdaVersionIsMultiple.cpp ├── 22.4 LambdaBinaryFunc.cpp ├── 22.5 LambdaCaseInsensitiveSort.cpp ├── 22.Ex1 LambdaSort.cpp ├── 22.Ex2 LambdAddsNum.cpp ├── 23.1 UsingFind.cpp ├── 23.10 SortUniqueBS.cpp ├── 23.11 PartitionStablePartition.cpp ├── 23.12 LowerBoundUpperBound.cpp ├── 23.14 RangesConstrainedAlgorithms.cpp ├── 23.2 UsingCount.cpp ├── 23.3 UsingSearch.cpp ├── 23.4 FillAndFillN.cpp ├── 23.5 UsingGenerate.cpp ├── 23.6 UsingForEach.cpp ├── 23.7 UsingTransform.cpp ├── 23.8 CopyRemoveRemoveIf.cpp ├── 23.9 ReplaceReplaceIf.cpp ├── 23.Ex2 IteratorsCopy.cpp ├── 24.1 InstantiatingStack.cpp ├── 24.2 StackPushPop.cpp ├── 24.2 StackPushPop.cpp~ ├── 24.3 STLQueue.cpp ├── 24.4 QueueOperations.cpp ├── 24.5 InstantiatingPriorityQueue.cpp ├── 24.6 PriorityQueueOperations.cpp ├── 24.7 PriorityQueueWithPredicate.cpp ├── 25.1 InstantiatingBitSet.cpp ├── 25.2 BitSetOperations.cpp ├── 25.3 InstantiatingVectorBool.cpp ├── 25.4 UsingVectorBool.cpp ├── 25.Ex1 UseBitset.cpp ├── 26.1 MinimalSmartPtr.cpp ├── 26.2 DeepCopyPtr.cpp ├── 26.3 DestructiveCopyPtr.cpp ├── 26.4 UsingUniquePtr.cpp ├── 26.Ex2 FishUniquePtr.cpp ├── 27.1 CoutFormattingNumbers.cpp ├── 27.10 BinaryFile.cpp ├── 27.10s BinaryFile - String.cpp ├── 27.11 StringStream.cpp ├── 27.2 CoutNumPrecision.cpp ├── 27.3 CoutSetWSetFill.cpp ├── 27.4 SimpleInputUsingCin.cpp ├── 27.5 ReadingWordLine.cpp ├── 27.6 CinReadingWordLine.cpp ├── 27.7 UsingGetLine.cpp ├── 27.8 WritingToFile.cpp ├── 27.9 ReadingTextFile.cpp ├── 28.1 ExceptionSafetyInNew.cpp ├── 28.2 CatchingAType.cpp ├── 28.3 ExceptionOnDivideByZero.cpp ├── 28.4 StackUnwindingOnException.cpp ├── 28.5 CustomException.cpp ├── 29.1 ConceptFloatingPt.cpp ├── 29.2 UsingCommonConcepts.cpp ├── 29.3 ConceptsWithClasses.cpp ├── 29.4 ConceptDerivedFrom.cpp ├── 29.5 RangesIntro.cpp ├── 29.6 ViewsReverse.cpp ├── 29.7 CombiningAdaptors.cpp ├── 29.8 CombiningAdaptors.cpp ├── 29.Ex3 ViewReverseTransform.cpp ├── 3.1 VariablesDemo_MultiplyTwoNumbers.cpp ├── 3.2 VariablesScopeDemo.cpp ├── 3.3 GlobalVariablesDemo.cpp ├── 3.4 Operators_Signed_Unsigned_Overflow.cpp ├── 3.5 Using_sizeof.cpp ├── 3.6 UsingAuto.cpp ├── 3.7 Demo_Constants.cpp ├── 3.8 using constexpr.cpp ├── 3.9 Using_enum_Constants.cpp ├── 3.Ex3 Calculate_Area_Circumference.cpp ├── 30.1 jthread.cpp ├── 31.1 ModulesHelloWorld.cpp ├── 31.2 ImportModuleMain.cpp ├── 31.2 SimpleOperations.cpp ├── 31.2 SimpleOperations.ixx ├── 4.1 AccessingArrayElements.cpp ├── 4.2 WritingToArrayElements.cpp ├── 4.3 Declaring_Initializing_MD_Arrays.cpp ├── 4.4 Dynamic_Array_std_vector.cpp ├── 4.5 C-Style_HelloWorld.cpp ├── 4.6 UserInput_C_Style_String.cpp ├── 4.7 CPPStrings_std_string.cpp ├── 4.Ex1.cpp ├── 5.1 Check_ArithmeticOperators.cpp ├── 5.10 Operators_CompoundOperators.cpp ├── 5.11 Operator_sizeof.cpp ├── 5.2 Operators_PostFix_Prefix.cpp ├── 5.3 Operators_Relational_Equality.cpp ├── 5.4 ThreeWayComparisonOp.cpp ├── 5.5 Operators_Logical_AND_OR.cpp ├── 5.6 Operators_Logical_And_Or_If.cpp ├── 5.7 Operators_Logical_OR.cpp ├── 5.8 Operators_Bitwise.cpp ├── 5.9 Operators_BitwiseShift.cpp ├── 5.Ex3.cpp ├── 5.Quiz5.cpp ├── 6.1 Multiply_or_Add_if_else.cpp ├── 6.10 EnterValuesInAnArray_DisplayArray_for_loop.cpp ├── 6.11 MultiplyAdd_for_loop.cpp ├── 6.12 RangeBasedFor.cpp ├── 6.13 MultiplyAdd_InfiniteLoop_break_continue.cpp ├── 6.14 CrossMultiplyTwoArrays_NestedLoops.cpp ├── 6.15 IteratingMDArrays_nested_loops.cpp ├── 6.16 FibonacciSeries_usingLoops.cpp ├── 6.2 checkbounds.cpp ├── 6.3 Nested_if_check_Divisor.cpp ├── 6.4 WhatDaysOfWeekMean_if_else.cpp ├── 6.5 DaysOfWeek_switch_case.cpp ├── 6.6 ConditionalOperator_TernaryOperator.cpp ├── 6.7 MultiplyOrAdd_goto.cpp ├── 6.8 MultiplyOrAdd_while.cpp ├── 6.9 MultiplyAdd_do_while.cpp ├── 6.Ex1.cpp ├── 6.Ex2.cpp ├── 6.Ex3.cpp ├── 6.Ex4.cpp ├── 7.1 Functions_ComputingAreaCircumference.cpp ├── 7.10 Functions_Inline.cpp ├── 7.11 auto function return.cpp ├── 7.12 Functions_Lambda.cpp ├── 7.2 Functions_MultipleParameters_Cylinder.cpp ├── 7.3 Functions_SayingHelloWithoutParamsReturnValue.cpp ├── 7.4 Functions_DefaulParameters_Pi.cpp ├── 7.5 Functions_Recursive_Fibonacci.cpp ├── 7.6 Functions_MultipleReturns.cpp ├── 7.7 Functions_Overloaded_Area_CyclinderCircle.cpp ├── 7.8 Functions_Passing_Arrays.cpp ├── 7.9 Functions_PassingReference.cpp ├── 8.1 Pointers_ReferencingOperator.cpp ├── 8.10 Pointers_const_calculatingsquare.cpp ├── 8.11 Pointers_ArrayVar_IsAddressOfFirst.cpp ├── 8.12 Pointers_Arrays_Similarities.cpp ├── 8.13 Pointers_InvalidPtr.cpp ├── 8.14 Pointers_BetterProgramming.cpp ├── 8.15 CrashesNewWithoutExcHandler.cpp ├── 8.15 Pointers_new_exceptionhandler.cpp ├── 8.16 Pointers_new_nothrow.cpp ├── 8.17 References_Declaring_Initializing.cpp ├── 8.18 References_PassingArgsToFunctions.cpp ├── 8.19 References_Const.cpp ├── 8.2 Pointers_AssigningRefToPtr.cpp ├── 8.3 Pointers_OnePtrManyIntegers.cpp ├── 8.4 Pointers_Dereferencing_or_IndirectionOperator.cpp ├── 8.5 Pointers_AssigningUsingDerefOp.cpp ├── 8.6 Pointers_sizeof_Test.cpp ├── 8.7 Pointers_Using_new_delete.cpp ├── 8.8 Pointers_Using_new_delete_char_array.cpp ├── 8.9 Pointer_using_new_delete_multiple_elements.cpp ├── 9.1 ClassHuman.cpp ├── 9.10 Singleton.cpp ├── 9.11 MonsterDB_ForceConstructionOnFreeStore.cpp ├── 9.12 explicit constructors.cpp ├── 9.13 SizeOfClass.cpp ├── 9.14 FriendFunctions.cpp ├── 9.15 FriendClass.cpp ├── 9.16 UsingUnions.cpp ├── 9.17 AggregateInitializationClasses.cpp ├── 9.18 constexpr class.cpp ├── 9.2 DemonstratesAbstraction_HidesTrueAge.cpp ├── 9.3 ClassWithConstructors.cpp ├── 9.4 Overloaded Constructors.cpp ├── 9.5 OnlyOverloadedConstructor_NoDefault.cpp ├── 9.6 Constructor_InitializationLists.cpp ├── 9.7 FreeMemInDestructor.cpp ├── 9.8 ShallowCopy.cpp ├── 9.9 CopyConstructor_MyBuffer.cpp ├── 9.Ex3.cpp ├── 9.Ex4 Circle.cpp └── README.md /1.1 Hello World.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | std::cout << "Hello World" << std::endl; 6 | return 0; 7 | } -------------------------------------------------------------------------------- /1.Ex1 BasicMaths.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | int main() 3 | { 4 | int x = 8; 5 | int y = 6; 6 | std::cout << std::endl; 7 | std::cout << x - y << " " << x * y << " " << x + y; 8 | std::cout << std::endl; 9 | return 0; 10 | } -------------------------------------------------------------------------------- /1.Ex4 BugFree Ex3.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | int main() 3 | { 4 | std::cout << "Hello Buggy World \n"; 5 | return 0; 6 | } -------------------------------------------------------------------------------- /10.1 SimplePisceanClassHeirarchy.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Fish 5 | { 6 | public: 7 | bool isFreshWaterFish; 8 | 9 | void Swim() 10 | { 11 | if (isFreshWaterFish) 12 | cout << "Swims in lake" << endl; 13 | else 14 | cout << "Swims in sea" << endl; 15 | } 16 | }; 17 | 18 | class Tuna: public Fish 19 | { 20 | public: 21 | Tuna() 22 | { 23 | isFreshWaterFish = false; 24 | } 25 | }; 26 | 27 | class Carp: public Fish 28 | { 29 | public: 30 | Carp() 31 | { 32 | isFreshWaterFish = true; 33 | } 34 | }; 35 | 36 | int main() 37 | { 38 | Carp myLunch; 39 | Tuna myDinner; 40 | 41 | cout << "Getting my food to swim" << endl; 42 | 43 | cout << "Lunch: "; 44 | myLunch.Swim(); 45 | 46 | cout << "Dinner: "; 47 | myDinner.Swim(); 48 | 49 | return 0; 50 | } -------------------------------------------------------------------------------- /10.10 MultipleInheritance_Platypus.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Mammal 5 | { 6 | public: 7 | void FeedBabyMilk() 8 | { 9 | cout << "Mammal: Baby says glug!" << endl; 10 | } 11 | }; 12 | 13 | class Reptile 14 | { 15 | public: 16 | void SpitVenom() 17 | { 18 | cout << "Reptile: Shoo enemy! Spits venom!" << endl; 19 | } 20 | }; 21 | 22 | class Bird 23 | { 24 | public: 25 | void LayEggs() 26 | { 27 | cout << "Bird: Laid my eggs, am lighter now!" << endl; 28 | } 29 | }; 30 | // declaring class as final ensures that it cannot be derived from 31 | class Platypus final: public Mammal, public Bird, public Reptile 32 | { 33 | public: 34 | void Swim() 35 | { 36 | cout << "Platypus: Voila, I can swim!" << endl; 37 | } 38 | }; 39 | 40 | int main() 41 | { 42 | Platypus realFreak; 43 | realFreak.LayEggs(); 44 | realFreak.FeedBabyMilk(); 45 | realFreak.SpitVenom(); 46 | realFreak.Swim(); 47 | 48 | return 0; 49 | } -------------------------------------------------------------------------------- /10.2 Fish_With_protected.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Fish 5 | { 6 | protected: 7 | bool isFreshWaterFish; // accessible only to derived classes 8 | 9 | public: 10 | void Swim() 11 | { 12 | if (isFreshWaterFish) 13 | cout << "Swims in lake" << endl; 14 | else 15 | cout << "Swims in sea" << endl; 16 | } 17 | }; 18 | 19 | class Tuna: public Fish 20 | { 21 | public: 22 | Tuna() 23 | { 24 | isFreshWaterFish = false; // set base class protected member 25 | } 26 | }; 27 | 28 | class Carp: public Fish 29 | { 30 | public: 31 | Carp() 32 | { 33 | isFreshWaterFish = true; 34 | } 35 | }; 36 | 37 | int main() 38 | { 39 | Carp myLunch; 40 | Tuna myDinner; 41 | 42 | cout << "Getting my food to swim" << endl; 43 | 44 | cout << "Lunch: "; 45 | myLunch.Swim(); 46 | 47 | cout << "Dinner: "; 48 | myDinner.Swim(); 49 | 50 | // uncomment line below to see that protected members 51 | // are not accessible from outside the class heirarchy 52 | // myLunch.isFreshWaterFish = false; 53 | 54 | return 0; 55 | } -------------------------------------------------------------------------------- /10.3 Fish_WithBaseClassInstantiation.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Fish 5 | { 6 | protected: 7 | bool isFreshWaterFish; // accessible only to derived classes 8 | 9 | public: 10 | // Fish constructor 11 | Fish(bool isFreshWater) : isFreshWaterFish(isFreshWater){} 12 | 13 | void Swim() 14 | { 15 | if (isFreshWaterFish) 16 | cout << "Swims in lake" << endl; 17 | else 18 | cout << "Swims in sea" << endl; 19 | } 20 | }; 21 | 22 | class Tuna: public Fish 23 | { 24 | public: 25 | Tuna(): Fish(false) {} 26 | }; 27 | 28 | class Carp: public Fish 29 | { 30 | public: 31 | Carp(): Fish(true) {} 32 | }; 33 | 34 | int main() 35 | { 36 | Carp myLunch; 37 | Tuna myDinner; 38 | 39 | cout << "Getting my food to swim" << endl; 40 | 41 | cout << "Lunch: "; 42 | myLunch.Swim(); 43 | 44 | cout << "Dinner: "; 45 | myDinner.Swim(); 46 | 47 | return 0; 48 | } -------------------------------------------------------------------------------- /10.4 DerivedClassOverridingMethod.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Fish 5 | { 6 | private: 7 | bool isFreshWaterFish; 8 | 9 | public: 10 | // Fish constructor 11 | Fish(bool IsFreshWater) : isFreshWaterFish(IsFreshWater){} 12 | 13 | void Swim() 14 | { 15 | if (isFreshWaterFish) 16 | cout << "Swims in lake" << endl; 17 | else 18 | cout << "Swims in sea" << endl; 19 | } 20 | }; 21 | 22 | class Tuna: public Fish 23 | { 24 | public: 25 | Tuna(): Fish(false) {} 26 | 27 | void Swim() 28 | { 29 | cout << "Tuna swims real fast" << endl; 30 | } 31 | }; 32 | 33 | class Carp: public Fish 34 | { 35 | public: 36 | Carp(): Fish(true) {} 37 | 38 | void Swim() 39 | { 40 | cout << "Carp swims real slow" << endl; 41 | } 42 | }; 43 | 44 | int main() 45 | { 46 | Carp myLunch; 47 | Tuna myDinner; 48 | 49 | cout << "Getting my food to swim" << endl; 50 | 51 | cout << "Lunch: "; 52 | myLunch.Swim(); 53 | 54 | cout << "Dinner: "; 55 | myDinner.Swim(); 56 | 57 | return 0; 58 | } -------------------------------------------------------------------------------- /10.5 InvokingBaseMethods_InSpiteOverride.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Fish 5 | { 6 | private: 7 | bool isFreshWaterFish; 8 | 9 | public: 10 | // Fish constructor 11 | Fish(bool isFreshWater) : isFreshWaterFish(isFreshWater){} 12 | 13 | void Swim() 14 | { 15 | if (isFreshWaterFish) 16 | cout << "Swims in lake" << endl; 17 | else 18 | cout << "Swims in sea" << endl; 19 | } 20 | }; 21 | 22 | class Tuna: public Fish 23 | { 24 | public: 25 | Tuna(): Fish(false) {} 26 | 27 | void Swim() 28 | { 29 | cout << "Tuna swims real fast" << endl; 30 | } 31 | }; 32 | 33 | class Carp: public Fish 34 | { 35 | public: 36 | Carp(): Fish(true) {} 37 | 38 | void Swim() 39 | { 40 | cout << "Carp swims real slow" << endl; 41 | Fish::Swim(); 42 | } 43 | }; 44 | 45 | int main() 46 | { 47 | Carp myLunch; 48 | Tuna myDinner; 49 | 50 | cout << "Getting my food to swim" << endl; 51 | 52 | cout << "Lunch: "; 53 | myLunch.Swim(); 54 | 55 | cout << "Dinner: "; 56 | myDinner.Fish::Swim(); 57 | 58 | return 0; 59 | } -------------------------------------------------------------------------------- /10.6 MethodHiding.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Fish 5 | { 6 | public: 7 | void Swim() 8 | { 9 | cout << "Fish swims... !" << endl; 10 | } 11 | 12 | void Swim(bool isFreshWaterFish) 13 | { 14 | if (isFreshWaterFish) 15 | cout << "Swims in lake" << endl; 16 | else 17 | cout << "Swims in sea" << endl; 18 | } 19 | }; 20 | 21 | class Tuna: public Fish 22 | { 23 | public: 24 | void Swim() 25 | { 26 | cout << "Tuna swims real fast" << endl; 27 | } 28 | }; 29 | 30 | int main() 31 | { 32 | Tuna myDinner; 33 | 34 | cout << "Getting my food to swim" << endl; 35 | 36 | //uncomment line below to see failure because Tuna::Swim() hides Fish::Swim(bool) 37 | // myDinner.Swim(false); 38 | 39 | myDinner.Swim(); 40 | 41 | return 0; 42 | } -------------------------------------------------------------------------------- /10.6 Protected_SuperCar.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Motor 5 | { 6 | protected: 7 | void SwitchIgnition() 8 | { 9 | cout << "Ignition ON" << endl; 10 | } 11 | void PumpFuel() 12 | { 13 | cout << "Fuel in cylinders" << endl; 14 | } 15 | void FireCylinders() 16 | { 17 | cout << "Vroooom" << endl; 18 | } 19 | }; 20 | 21 | class Car:protected Motor 22 | { 23 | public: 24 | void Move() 25 | { 26 | SwitchIgnition(); 27 | PumpFuel(); 28 | FireCylinders(); 29 | } 30 | }; 31 | 32 | class SuperCar:protected Car 33 | { 34 | public: 35 | void Move() 36 | { 37 | SwitchIgnition(); 38 | PumpFuel(); 39 | FireCylinders(); 40 | FireCylinders(); 41 | FireCylinders(); 42 | } 43 | }; 44 | 45 | int main() 46 | { 47 | SuperCar myDreamCar; 48 | myDreamCar.Move(); 49 | 50 | return 0; 51 | } -------------------------------------------------------------------------------- /10.7 SequenceConstructionDestruction.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class FishDummyMember 5 | { 6 | public: 7 | FishDummyMember() 8 | { 9 | cout << "FishDummyMember constructor" << endl; 10 | } 11 | 12 | ~FishDummyMember() 13 | { 14 | cout << "FishDummyMember destructor" << endl; 15 | } 16 | }; 17 | 18 | class Fish 19 | { 20 | protected: 21 | FishDummyMember dummy; 22 | 23 | public: 24 | // Fish constructor 25 | Fish() 26 | { 27 | cout << "Fish constructor" << endl; 28 | } 29 | 30 | ~Fish() 31 | { 32 | cout << "Fish destructor" << endl; 33 | } 34 | }; 35 | 36 | class TunaDummyMember 37 | { 38 | public: 39 | TunaDummyMember() 40 | { 41 | cout << "TunaDummyMember constructor" << endl; 42 | } 43 | 44 | ~TunaDummyMember() 45 | { 46 | cout << "TunaDummyMember destructor" << endl; 47 | } 48 | }; 49 | 50 | class Tuna: public Fish 51 | { 52 | private: 53 | TunaDummyMember dummy; 54 | 55 | public: 56 | Tuna() 57 | { 58 | cout << "Tuna constructor" << endl; 59 | } 60 | ~Tuna() 61 | { 62 | cout << "Tuna destructor" << endl; 63 | } 64 | 65 | }; 66 | 67 | int main() 68 | { 69 | Tuna myDinner; 70 | } -------------------------------------------------------------------------------- /10.8 PvtInheritanceCarMotor.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Motor 5 | { 6 | public: 7 | void SwitchIgnition() 8 | { 9 | cout << "Ignition ON" << endl; 10 | } 11 | void PumpFuel() 12 | { 13 | cout << "Fuel in cylinders" << endl; 14 | } 15 | void FireCylinders() 16 | { 17 | cout << "Vroooom" << endl; 18 | } 19 | }; 20 | 21 | class Car:private Motor 22 | { 23 | public: 24 | void Move() 25 | { 26 | SwitchIgnition(); 27 | PumpFuel(); 28 | FireCylinders(); 29 | } 30 | }; 31 | 32 | int main() 33 | { 34 | Car myDreamCar; 35 | myDreamCar.Move(); 36 | 37 | return 0; 38 | } -------------------------------------------------------------------------------- /10.9 ProtectedInheritance: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/learncppnow/9E/97b254e0eb394ab67553d9f4f61736714c884af0/10.9 ProtectedInheritance -------------------------------------------------------------------------------- /10.9 ProtectedInheritance.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Motor 5 | { 6 | public: 7 | void SwitchIgnition() 8 | { 9 | cout << "Ignition ON" << endl; 10 | } 11 | void PumpFuel() 12 | { 13 | cout << "Fuel in cylinders" << endl; 14 | } 15 | void FireCylinders() 16 | { 17 | cout << "Vroooom" << endl; 18 | } 19 | }; 20 | 21 | class Car :protected Motor 22 | { 23 | public: 24 | void Move() 25 | { 26 | SwitchIgnition(); 27 | PumpFuel(); 28 | FireCylinders(); 29 | } 30 | }; 31 | 32 | class RaceCar :protected Car 33 | { 34 | public: 35 | void Move() 36 | { 37 | SwitchIgnition(); // RaceCar has access to members of 38 | PumpFuel(); // base Motor due to "protected" inheritance 39 | FireCylinders(); // between RaceCar & Car, Car & Motor 40 | FireCylinders(); 41 | FireCylinders(); 42 | } 43 | }; 44 | 45 | int main() 46 | { 47 | RaceCar myDreamCar; 48 | myDreamCar.Move(); 49 | 50 | return 0; 51 | } -------------------------------------------------------------------------------- /11.1 InvokingSwimUsingFishPtr.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Fish 5 | { 6 | public: 7 | void Swim() 8 | { 9 | cout << "Fish swims!" << endl; 10 | } 11 | }; 12 | 13 | class Tuna:public Fish 14 | { 15 | public: 16 | // override Fish::Swim 17 | void Swim() 18 | { 19 | cout << "Tuna swims!" << endl; 20 | } 21 | }; 22 | 23 | void MakeFishSwim(Fish& inputFish) 24 | { 25 | // calling Fish::Swim 26 | inputFish.Swim(); 27 | } 28 | 29 | int main() 30 | { 31 | Tuna myDinner; 32 | 33 | // calling Tuna::Swim 34 | myDinner.Swim(); 35 | 36 | // sending Tuna as Fish 37 | MakeFishSwim(myDinner); 38 | 39 | return 0; 40 | } -------------------------------------------------------------------------------- /11.2 FishSwim_VirtualMethod.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Fish 5 | { 6 | public: 7 | virtual void Swim() 8 | { 9 | cout << "Fish swims!" << endl; 10 | } 11 | }; 12 | 13 | class Tuna:public Fish 14 | { 15 | public: 16 | // override Fish::Swim 17 | void Swim() 18 | { 19 | cout << "Tuna swims!" << endl; 20 | } 21 | }; 22 | 23 | class Carp:public Fish 24 | { 25 | public: 26 | // override Fish::Swim 27 | void Swim() 28 | { 29 | cout << "Carp swims!" << endl; 30 | } 31 | }; 32 | 33 | void MakeFishSwim(Fish& InputFish) 34 | { 35 | // calling Swim 36 | InputFish.Swim(); 37 | } 38 | 39 | int main() 40 | { 41 | Tuna myDinner; 42 | Carp myLunch; 43 | 44 | // sending Tuna as Fish 45 | MakeFishSwim(myDinner); 46 | 47 | // sending Carp as Fish 48 | MakeFishSwim(myLunch); 49 | 50 | return 0; 51 | } -------------------------------------------------------------------------------- /11.3 WithoutVirtualDestructors.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Fish 5 | { 6 | public: 7 | Fish() 8 | { 9 | cout << "Constructed Fish" << endl; 10 | } 11 | ~Fish() 12 | { 13 | cout << "Destroyed Fish" << endl; 14 | } 15 | }; 16 | 17 | class Tuna:public Fish 18 | { 19 | public: 20 | Tuna() 21 | { 22 | cout << "Constructed Tuna" << endl; 23 | } 24 | ~Tuna() 25 | { 26 | cout << "Destroyed Tuna" << endl; 27 | } 28 | }; 29 | 30 | void DeleteFish(Fish* pFish) 31 | { 32 | delete pFish; 33 | } 34 | 35 | int main() 36 | { 37 | cout << "Allocating a Tuna on the free store:" << endl; 38 | Tuna* pTuna = new Tuna; 39 | cout << "Deleting the Tuna: " << endl; 40 | DeleteFish(pTuna); 41 | 42 | cout << "Instantiating a Tuna on the stack:" << endl; 43 | Tuna myDinner; 44 | cout << "Automatic destruction as it goes out of scope: " << endl; 45 | 46 | return 0; 47 | } -------------------------------------------------------------------------------- /11.4 VirtualDestructors.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Fish 5 | { 6 | public: 7 | Fish() 8 | { 9 | cout << "Constructed Fish" << endl; 10 | } 11 | virtual ~Fish() // virtual destructor! 12 | { 13 | cout << "Destroyed Fish" << endl; 14 | } 15 | }; 16 | 17 | class Tuna:public Fish 18 | { 19 | public: 20 | Tuna() 21 | { 22 | cout << "Constructed Tuna" << endl; 23 | } 24 | ~Tuna() 25 | { 26 | cout << "Destroyed Tuna" << endl; 27 | } 28 | }; 29 | 30 | void DeleteFishMemory(Fish* pFish) 31 | { 32 | delete pFish; 33 | } 34 | 35 | int main() 36 | { 37 | cout << "Allocating a Tuna on the free store:" << endl; 38 | Tuna* pTuna = new Tuna; 39 | cout << "Deleting the Tuna: " << endl; 40 | DeleteFishMemory(pTuna); 41 | 42 | cout << "Instantiating a Tuna on the stack:" << endl; 43 | Tuna myDinner; 44 | cout << "Automatic destruction as it goes out of scope: " << endl; 45 | 46 | return 0; 47 | } -------------------------------------------------------------------------------- /11.5 SizeofBaseClassWithVirtualFunctions.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class SimpleClass 5 | { 6 | int a, b; 7 | 8 | public: 9 | void DoSomething() {} 10 | }; 11 | 12 | class Base 13 | { 14 | int a, b; 15 | 16 | public: 17 | virtual void DoSomething() {} 18 | }; 19 | 20 | int main() 21 | { 22 | cout << "sizeof(SimpleClass) = " << sizeof(SimpleClass) << endl; 23 | cout << "sizeof(Base) = " << sizeof(Base) << endl; 24 | 25 | return 0; 26 | } -------------------------------------------------------------------------------- /11.6 FishABC.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Fish 5 | { 6 | public: 7 | // define a pure virtual function Swim 8 | virtual void Swim() = 0; 9 | }; 10 | 11 | class Tuna:public Fish 12 | { 13 | public: 14 | void Swim() 15 | { 16 | cout << "Tuna swims fast in the sea!" << endl; 17 | } 18 | }; 19 | 20 | class Carp:public Fish 21 | { 22 | void Swim() 23 | { 24 | cout << "Carp swims slow in the lake!" << endl; 25 | } 26 | }; 27 | 28 | void MakeFishSwim(Fish& inputFish) 29 | { 30 | inputFish.Swim(); 31 | } 32 | 33 | int main() 34 | { 35 | // Fish myFish; // Fails, cannot instantiate an ABC 36 | Carp myLunch; 37 | Tuna myDinner; 38 | 39 | MakeFishSwim(myLunch); 40 | MakeFishSwim(myDinner); 41 | 42 | return 0; 43 | } -------------------------------------------------------------------------------- /11.7 MultipleInheritance_Platypus.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Animal 5 | { 6 | public: 7 | Animal() 8 | { 9 | cout << "Animal constructor" << endl; 10 | } 11 | 12 | int age; 13 | }; 14 | 15 | class Mammal:public Animal {}; 16 | class Bird:public Animal {}; 17 | class Reptile:public Animal {}; 18 | 19 | class Platypus :public Mammal, public Bird, public Reptile 20 | { 21 | public: 22 | Platypus() 23 | { 24 | cout << "Platypus constructor" << endl; 25 | } 26 | }; 27 | 28 | int main() 29 | { 30 | Platypus duckBilledP; 31 | 32 | // uncomment next line of code to see compile failure because 33 | // age is ambiguous: three instances of base Animal per Platypus 34 | // duckBilledP.age = 25; 35 | 36 | return 0; 37 | } -------------------------------------------------------------------------------- /11.8 VirtualInheritance_Platypus.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Animal 5 | { 6 | public: 7 | Animal() 8 | { 9 | cout << "Animal constructor" << endl; 10 | } 11 | 12 | int age; 13 | }; 14 | 15 | class Mammal:public virtual Animal {}; 16 | class Bird:public virtual Animal {}; 17 | class Reptile:public virtual Animal {}; 18 | 19 | class Platypus final:public Mammal, public Bird, public Reptile 20 | { 21 | public: 22 | Platypus() 23 | { 24 | cout << "Platypus constructor" << endl; 25 | } 26 | }; 27 | 28 | int main() 29 | { 30 | Platypus duckBilledP; 31 | 32 | // no compile error as there is only one Animal::age 33 | duckBilledP.age = 25; 34 | 35 | return 0; 36 | } -------------------------------------------------------------------------------- /11.Ex3.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Vehicle 5 | { 6 | public: 7 | Vehicle() { cout << "Consructor Vehicle" << endl; } 8 | ~Vehicle() { cout << "Destructor Vehicle" << endl; } 9 | }; 10 | class Car : public Vehicle 11 | { 12 | public: 13 | Car() { cout << "Consructor Car" << endl; } 14 | ~Car() { cout << "Destructor Vehicle" << endl; } 15 | }; 16 | 17 | 18 | int main() 19 | { 20 | Vehicle* pMyRacer = new Car; 21 | delete pMyRacer; 22 | 23 | return 0; 24 | } -------------------------------------------------------------------------------- /11.Quiz1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Shape 5 | { 6 | public: 7 | virtual double Area() = 0; 8 | virtual void Print() = 0; 9 | }; 10 | 11 | class Circle: public Shape 12 | { 13 | double Radius; 14 | public: 15 | Circle(double inputRadius) : Radius(inputRadius) {} 16 | 17 | double Area() override 18 | { 19 | return 3.1415 * Radius * Radius; 20 | } 21 | 22 | void Print() override 23 | { 24 | cout << "Circle says hello!" << endl; 25 | } 26 | }; 27 | 28 | class Triangle: public Shape 29 | { 30 | double Base, Height; 31 | public: 32 | Triangle(double inputBase, double inputHeight) : Base(inputBase), Height(inputHeight) {} 33 | 34 | double Area() override 35 | { 36 | return 0.5 * Base * Height; 37 | } 38 | 39 | void Print() override 40 | { 41 | cout << "Triangle says hello!" << endl; 42 | } 43 | }; 44 | 45 | int main() 46 | { 47 | Circle myRing(5); 48 | Triangle myWarningTriangle(6.6, 2); 49 | 50 | cout << "Area of circle: " << myRing.Area() << endl; 51 | cout << "Area of triangle: " << myWarningTriangle.Area() << endl; 52 | 53 | myRing.Print(); 54 | myWarningTriangle.Print(); 55 | 56 | return 0; 57 | } -------------------------------------------------------------------------------- /12.11 FunctionObjects_Functors_Operator().cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Display 6 | { 7 | public: 8 | void operator () (string input) const 9 | { 10 | cout << input << endl; 11 | } 12 | }; 13 | 14 | int main () 15 | { 16 | Display displayFuncObj; 17 | 18 | // equivalent to displayFuncObj.operator () ("Display this string!"); 19 | displayFuncObj ("Display this string!"); 20 | 21 | return 0; 22 | } -------------------------------------------------------------------------------- /12.13 UDLtoKelvin.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct Temperature 5 | { 6 | double Kelvin; 7 | Temperature(long double kelvin) : Kelvin(kelvin) {} 8 | }; 9 | 10 | Temperature operator"" _C(long double celsius) 11 | { 12 | return Temperature(celsius + 273); 13 | } 14 | 15 | Temperature operator "" _F(long double fahrenheit) 16 | { 17 | return Temperature((fahrenheit + 459.67) * 5 / 9); 18 | } 19 | 20 | int main() 21 | { 22 | Temperature k1 = 31.73_F; 23 | Temperature k2 = 0.0_C; 24 | 25 | cout << "k1 is " << k1.Kelvin << " Kelvin" << endl; 26 | cout << "k2 is " << k2.Kelvin << " Kelvin" << endl; 27 | 28 | return 0; 29 | } -------------------------------------------------------------------------------- /12.2 OperatorConstCharPtr.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include // new include for ostringstream 3 | #include 4 | using namespace std; 5 | 6 | class Date 7 | { 8 | private: 9 | int day, month, year; 10 | string dateInString; 11 | 12 | public: 13 | Date(int inMonth, int inDay, int inYear) 14 | : month(inMonth), day(inDay), year(inYear) {}; 15 | 16 | operator const char*() 17 | { 18 | ostringstream formattedDate; // assists string construction 19 | formattedDate << month << " / " << day << " / " << year; 20 | 21 | dateInString = formattedDate.str(); 22 | return dateInString.c_str(); 23 | } 24 | }; 25 | 26 | int main () 27 | { 28 | Date holiday (12, 25, 2021); 29 | 30 | cout << "Holiday is on: " << holiday << endl; 31 | 32 | // string strHoliday (holiday); // OK! 33 | // strHoliday = Date(11, 11, 2021); // also OK! 34 | 35 | return 0; 36 | } -------------------------------------------------------------------------------- /12.3 UniquePtr.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include // new include to use unique_ptr 3 | using namespace std; 4 | 5 | class Date 6 | { 7 | private: 8 | int day, month, year; 9 | string dateInString; 10 | 11 | public: 12 | Date(int inMonth, int inDay, int inYear) 13 | : month(inMonth), day(inDay), year(inYear) {}; 14 | 15 | void DisplayDate() 16 | { 17 | cout << month << " / " << day << " / " << year << endl; 18 | } 19 | }; 20 | 21 | int main() 22 | { 23 | unique_ptr smartIntPtr(new int); 24 | *smartIntPtr = 42; 25 | 26 | // Use smart pointer type like an int* 27 | cout << "Integer value is: " << *smartIntPtr << endl; 28 | 29 | unique_ptr smartHoliday (new Date(12, 25, 2021)); 30 | cout << "The new instance of date contains: "; 31 | 32 | // use smartHoliday just as you would a Date* 33 | smartHoliday->DisplayDate(); 34 | 35 | return 0; // smart pointers do the deallocation for you 36 | } -------------------------------------------------------------------------------- /12.4 BinaryAdditionSubtractionOperator.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Date 5 | { 6 | private: 7 | int day, month, year; 8 | string dateInString; 9 | 10 | public: 11 | Date(int inMonth, int inDay, int inYear) 12 | : month(inMonth), day(inDay), year(inYear) {}; 13 | 14 | Date operator + (int daysToAdd) // binary addition 15 | { 16 | Date newDate (month, day + daysToAdd, year); 17 | return newDate; 18 | } 19 | 20 | Date operator - (int daysToSub) // binary subtraction 21 | { 22 | return Date(month, day - daysToSub, year); 23 | } 24 | 25 | void DisplayDate() 26 | { 27 | cout << month << " / " << day << " / " << year << endl; 28 | } 29 | }; 30 | 31 | int main() 32 | { 33 | Date holiday (12, 25, 2021); 34 | cout << "Holiday on: "; 35 | holiday.DisplayDate (); 36 | 37 | Date previousHoliday (holiday - 19); 38 | cout << "Previous holiday on: "; 39 | previousHoliday.DisplayDate(); 40 | 41 | Date nextHoliday(holiday + 6); 42 | cout << "Next holiday on: "; 43 | nextHoliday.DisplayDate (); 44 | 45 | return 0; 46 | } -------------------------------------------------------------------------------- /12.5 AddSubAssignment.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Date 5 | { 6 | private: 7 | int day, month, year; 8 | 9 | public: 10 | Date(int inMonth, int inDay, int inYear) 11 | : month(inMonth), day(inDay), year(inYear) {} 12 | 13 | void operator+= (int daysToAdd) // addition assignment 14 | { 15 | day += daysToAdd; 16 | } 17 | 18 | void operator-= (int daysToSub) // subtraction assignment 19 | { 20 | day -= daysToSub; 21 | } 22 | 23 | void DisplayDate() 24 | { 25 | cout << month << " / " << day << " / " << year << endl; 26 | } 27 | }; 28 | 29 | int main() 30 | { 31 | Date holiday (12, 25, 2021); 32 | cout << "holiday is on: "; 33 | holiday.DisplayDate (); 34 | 35 | cout << "holiday -= 19 gives: "; 36 | holiday -= 19; 37 | holiday.DisplayDate(); 38 | 39 | cout << "holiday += 25 gives: "; 40 | holiday += 25; 41 | holiday.DisplayDate (); 42 | 43 | return 0; 44 | } -------------------------------------------------------------------------------- /12.6 Equality_Inequality_Comparison.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Date 5 | { 6 | private: 7 | int day, month, year; 8 | 9 | public: 10 | Date(int inMonth, int inDay, int inYear) 11 | : month(inMonth), day(inDay), year(inYear) {} 12 | 13 | bool operator== (const Date& compareTo) const 14 | { 15 | return ((day == compareTo.day) 16 | && (month == compareTo.month) 17 | && (year == compareTo.year)); 18 | } 19 | 20 | bool operator!= (const Date& compareTo) const 21 | { 22 | return !(this->operator==(compareTo)); 23 | } 24 | 25 | void DisplayDate() 26 | { 27 | cout << month << " / " << day << " / " << year << endl; 28 | } 29 | }; 30 | 31 | int main() 32 | { 33 | Date holiday1 (12, 25, 2021); 34 | Date holiday2 (12, 31, 2021); 35 | 36 | cout << "holiday 1 is: "; 37 | holiday1.DisplayDate(); 38 | cout << "holiday 2 is: "; 39 | holiday2.DisplayDate(); 40 | 41 | if (holiday1 == holiday2) 42 | cout << "Equality operator: The two are on the same day" << endl; 43 | else 44 | cout << "Equality operator: The two are on different days" << endl; 45 | 46 | if (holiday1 != holiday2) 47 | cout << "Inequality operator: The two are on different days" << endl; 48 | else 49 | cout << "Inequality operator: The two are on the same day" << endl; 50 | 51 | return 0; 52 | } -------------------------------------------------------------------------------- /14.1 MacroConstants.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | #define ARRAY_LENGTH 25 6 | #define PI 3.1416 7 | #define MY_DOUBLE double 8 | #define FAV_WHISKY "Jack Daniels" 9 | 10 | /* 11 | // Superior alternatives (comment those above when you uncomment these) 12 | const int ARRAY_LENGTH = 25; 13 | const double PI = 3.1416; 14 | typedef double MY_DOUBLE; 15 | const char* FAV_WHISKY = "Jack Daniels"; 16 | */ 17 | 18 | int main() 19 | { 20 | int MyNumbers [ARRAY_LENGTH] = {0}; 21 | cout << "Array's length: " << sizeof(MyNumbers) / sizeof(int) << endl; 22 | 23 | cout << "Enter a radius: "; 24 | MY_DOUBLE Radius = 0; 25 | cin >> Radius; 26 | cout << "Area is: " << PI * Radius * Radius << endl; 27 | 28 | string FavoriteWhisky (FAV_WHISKY); 29 | cout << "My favorite drink is: " << FAV_WHISKY << endl; 30 | 31 | return 0; 32 | } -------------------------------------------------------------------------------- /14.2 MacroFunctions.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | #define SQUARE(x) ((x) * (x)) 6 | #define PI 3.1416 7 | #define AREA_CIRCLE(r) (PI*(r)*(r)) 8 | // #define AREA_CIRCLE(r) (PI*r*r) // uncomment this to understand why brackets are important (comment previous line) 9 | #define MAX(a, b) (((a) > (b)) ? (a) : (b)) 10 | #define MIN(a, b) (((a) < (b)) ? (a) : (b)) 11 | 12 | int main() 13 | { 14 | cout << "Enter an integer: "; 15 | int num1 = 0; 16 | cin >> num1; 17 | 18 | cout << "SQUARE(" << num1 << ") = " << SQUARE(num1) << endl; 19 | cout << "Area of a circle with radius " << num1 << " is: "; 20 | cout << AREA_CIRCLE(num1) << endl; 21 | 22 | cout << "Enter another integer: "; 23 | int num2 = 0; 24 | cin >> num2; 25 | 26 | cout << "MIN(" << num1 << ", " << num2 << ") = "; 27 | cout << MIN (num1, num2) << endl; 28 | 29 | cout << "MAX(" << num1 << ", " << num2 << ") = "; 30 | cout << MAX (num1, num2) << endl; 31 | 32 | return 0; 33 | } -------------------------------------------------------------------------------- /14.3 TemplateFunctionGetMax.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | template 6 | const Type& GetMax (const Type& value1, const Type& value2) 7 | { 8 | if (value1 > value2) 9 | return value1; 10 | else 11 | return value2; 12 | } 13 | 14 | template 15 | void DisplayComparison(const Type& value1, const Type& value2) 16 | { 17 | cout << "GetMax(" << value1 << ", " << value2 << ") = "; 18 | cout << GetMax(value1, value2) << endl; 19 | } 20 | 21 | int main() 22 | { 23 | int num1 = -101, num2 = 2011; 24 | DisplayComparison(num1, num2); 25 | 26 | double d1 = 3.14, d2 = 3.1416; 27 | DisplayComparison(d1, d2); 28 | 29 | string name1("Jack"), name2("John"); 30 | DisplayComparison(name1, name2); 31 | 32 | return 0; 33 | } -------------------------------------------------------------------------------- /14.4 HoldsPairWithMain.cpp: -------------------------------------------------------------------------------- 1 | // template with default params: int & double 2 | template 3 | class HoldsPair 4 | { 5 | private: 6 | T1 value1; 7 | T2 value2; 8 | public: 9 | HoldsPair(const T1& val1, const T2& val2) // constructor 10 | : value1(val1), value2(val2) {} 11 | 12 | // Accessor functions 13 | const T1& GetFirstValue() const 14 | { 15 | return value1; 16 | } 17 | 18 | const T2& GetSecondValue() const 19 | { 20 | return value2; 21 | } 22 | }; 23 | 24 | #include 25 | using namespace std; 26 | 27 | int main () 28 | { 29 | HoldsPair <> pairIntDbl (300, 10.09); 30 | HoldsPair pairShortStr(25, "Learn templates, love C++"); 31 | 32 | cout << "The first object contains -" << endl; 33 | cout << "Value 1: " << pairIntDbl.GetFirstValue() << endl; 34 | cout << "Value 2: " << pairIntDbl.GetSecondValue() << endl; 35 | 36 | cout << "The second object contains -" << endl; 37 | cout << "Value 1: " << pairShortStr.GetFirstValue() << endl; 38 | cout << "Value 2: " << pairShortStr.GetSecondValue() << endl; 39 | 40 | return 0; 41 | } -------------------------------------------------------------------------------- /14.5 TemplateSpecialization.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | template 5 | class HoldsPair 6 | { 7 | private: 8 | T1 value1; 9 | T2 value2; 10 | public: 11 | HoldsPair(const T1& val1, const T2& val2) // constructor 12 | : value1(val1), value2(val2) {} 13 | 14 | // Accessor functions 15 | const T1& GetFirstValue() const; 16 | const T2& GetSecondValue() const; 17 | }; 18 | 19 | // specialization of HoldsPair for types int & int here 20 | template<> class HoldsPair 21 | { 22 | private: 23 | int value1; 24 | int value2; 25 | string strFun; 26 | public: 27 | HoldsPair(const int& val1, const int& val2) // constructor 28 | : value1(val1), value2(val2) {} 29 | 30 | const int & GetFirstValue() const 31 | { 32 | cout << "Returning integer " << value1 << endl; 33 | return value1; 34 | } 35 | }; 36 | 37 | int main() 38 | { 39 | HoldsPair pairIntInt(222, 333); 40 | pairIntInt.GetFirstValue(); 41 | 42 | return 0; 43 | } -------------------------------------------------------------------------------- /14.6 StaticWithinTemplate.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | template 5 | class TestStatic 6 | { 7 | public: 8 | static T staticVal; 9 | }; 10 | 11 | // static member initialization 12 | template T TestStatic::staticVal; 13 | 14 | int main() 15 | { 16 | TestStatic intInstance; 17 | cout << "Setting staticVal for intInstance to 2021" << endl; 18 | intInstance.staticVal = 2021; 19 | 20 | TestStatic dblnstance; 21 | cout << "Setting staticVal for dblnstance to 1011.022" << endl; 22 | dblnstance.staticVal = 1011.022; 23 | 24 | cout << "intInstance.staticVal = " << intInstance.staticVal << endl; 25 | cout << "dblnstance.staticVal = " << dblnstance.staticVal << endl; 26 | 27 | return 0; 28 | } -------------------------------------------------------------------------------- /14.7 VariableTemplatesSum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | template 5 | void Sum(Res& result, ValType& val) 6 | { 7 | result = result + val; 8 | } 9 | 10 | template 11 | void Sum(Res& result, First val1, Rest... numN) 12 | { 13 | result = result + val1; // use sizeof...(numN) to find number of variadic parameters 14 | return Sum(result, numN ...); 15 | } 16 | 17 | int main() 18 | { 19 | double dResult = 0; 20 | Sum (dResult, 3.14, 4.56, 1.1111); 21 | cout << "dResult = " << dResult << endl; 22 | 23 | string strResult; 24 | Sum (strResult, "Hello ", "World"); 25 | cout << "strResult = " << strResult.c_str() << endl; 26 | 27 | return 0; 28 | } -------------------------------------------------------------------------------- /14.8 Tuple.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | template 7 | void DisplayTupleInfo(tupleType& tup) 8 | { 9 | const int numMembers = tuple_size::value; 10 | cout << "Num elements in tuple: " << numMembers << endl; 11 | cout << "Last element value: " << get(tup) << endl; 12 | } 13 | 14 | int main() 15 | { 16 | tuple tup1(make_tuple(101, 's', "Hello Tuple!")); 17 | DisplayTupleInfo(tup1); 18 | 19 | auto tup2(make_tuple(3.14, false)); 20 | DisplayTupleInfo(tup2); 21 | 22 | auto concatTup(tuple_cat(tup2, tup1)); // contains tup2, tup1 members 23 | DisplayTupleInfo(concatTup); 24 | 25 | double pi; 26 | string sentence; 27 | tie(pi, ignore, ignore, ignore, sentence) = concatTup; 28 | cout << "Unpacked! Pi: " << pi << " and \"" << sentence << "\"" << endl; 29 | 30 | return 0; 31 | } -------------------------------------------------------------------------------- /14.9 StaticAssert.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | template 4 | class OnlyInt 5 | { 6 | public: 7 | OnlyInt() 8 | { 9 | static_assert(std::is_integral::value, "Only integers please!"); 10 | } 11 | }; 12 | 13 | int main() 14 | { 15 | OnlyInt test1; // OK! 16 | // OnlyInt test2; // Error! 17 | 18 | return 0; 19 | } -------------------------------------------------------------------------------- /14.Ex6 DisplayVariadicTemp.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void Display() 5 | { 6 | } 7 | 8 | template void Display(First a, Last... U) 9 | { 10 | cout << a << endl; 11 | Display(U...); 12 | } 13 | 14 | 15 | int main() 16 | { 17 | Display('a'); 18 | Display(3.14); 19 | Display('a', 3.14); 20 | Display('z', 3.14567, "The power of variadic templates!"); 21 | 22 | return 0; 23 | } -------------------------------------------------------------------------------- /15.1 ContainerIteratorRelationship.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int main () 7 | { 8 | // A dynamic array of integers 9 | vector intArray; 10 | 11 | // Insert sample integers into the array 12 | intArray.push_back (50); 13 | intArray.push_back (2991); 14 | intArray.push_back (23); 15 | intArray.push_back (9999); 16 | 17 | cout << "The contents of the vector are: " << endl; 18 | 19 | // Walk the vector and read values using an iterator 20 | vector::iterator arrIterator = intArray.begin (); 21 | 22 | while (arrIterator != intArray.end ()) 23 | { 24 | // Write the value to the screen 25 | cout << *arrIterator << endl; 26 | 27 | // Increment the iterator to access the next element 28 | ++ arrIterator; 29 | } 30 | 31 | // Find an element (say 2991) in the array using the 'find' algorithm... 32 | vector::iterator elFound = find (intArray.begin (), 33 | intArray.end (), 2991); 34 | 35 | // Check if value was found 36 | if (elFound != intArray.end ()) 37 | { 38 | // Value was found... Determine position in the array: 39 | int elPos = distance (intArray.begin (), elFound); 40 | cout << "Value "<< *elFound; 41 | cout << " found in the vector at position: " << elPos << endl; 42 | } 43 | 44 | return 0; 45 | } 46 | -------------------------------------------------------------------------------- /16.1 STLStringInstantiationCopy.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | using namespace std; 7 | const char* constCStyleString = "Hello String!"; 8 | cout << "Constant string is: " << constCStyleString << endl; 9 | 10 | std::string strFromConst(constCStyleString); // constructor 11 | cout << "strFromConst is: " << strFromConst << endl; 12 | 13 | std::string str2("Hello String!"); 14 | std::string str2Copy(str2); 15 | cout << "str2Copy is: " << str2Copy << endl; 16 | 17 | // Initialize a string to the first 5 characters of another 18 | std::string strPartialCopy(constCStyleString, 5); 19 | cout << "strPartialCopy is: " << strPartialCopy << endl; 20 | 21 | // Initialize a string object to contain 10 'a's 22 | std::string strRepeatChars(10, 'a'); 23 | cout << "strRepeatChars is: " << strRepeatChars << endl; 24 | 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /16.3 ConcatenateAdditionAssignmentAppend.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | using namespace std; 7 | 8 | string strSample1("Hello"); 9 | string strSample2(" String!"); 10 | 11 | // Concatenate 12 | strSample1 += strSample2; 13 | cout << strSample1 << endl << endl; 14 | 15 | string strSample3(" Fun is not needing to use pointers!"); 16 | strSample1.append(strSample3); 17 | cout << strSample1 << endl << endl; 18 | 19 | const char* constCStyleString = " You however still can!"; 20 | strSample1.append(constCStyleString); 21 | cout << strSample1 << endl; 22 | 23 | return 0; 24 | } -------------------------------------------------------------------------------- /16.5 StringTruncate.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int main() 6 | { 7 | using namespace std; 8 | 9 | string sampleStr("Hello String! Wake up to a beautiful day!"); 10 | cout << "The original sample string is: " << endl; 11 | cout << sampleStr << endl << endl; 12 | 13 | // Delete characters from the string given position and count 14 | cout << "Truncating the second sentence: " << endl; 15 | sampleStr.erase(13, 28); 16 | cout << sampleStr << endl << endl; 17 | 18 | // Find a character 'S' in the string using STL find algorithm 19 | auto iCharS = find(sampleStr.begin(), 20 | sampleStr.end(), 'S'); 21 | 22 | // If character found, 'erase' to deletes a character 23 | cout << "Erasing character 'S' from the sample string:" << endl; 24 | if(iCharS != sampleStr.end()) 25 | sampleStr.erase(iCharS); 26 | 27 | cout << sampleStr << endl << endl; 28 | 29 | // Erase a range of characters using an overloaded version of erase() 30 | cout << "Erasing a range between begin() and end(): " << endl; 31 | sampleStr.erase(sampleStr.begin(), sampleStr.end()); 32 | 33 | // Verify the length after the erase() operation above 34 | if(sampleStr.length() == 0) 35 | cout << "The string is empty" << endl; 36 | 37 | return 0; 38 | } -------------------------------------------------------------------------------- /16.6 StringReverse.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int main() 6 | { 7 | using namespace std; 8 | 9 | string sampleStr("Hello String! We will reverse you!"); 10 | cout << "The original sample string is: " << endl; 11 | cout << sampleStr << endl << endl; 12 | 13 | reverse(sampleStr.begin(), sampleStr.end()); 14 | 15 | cout << "After applying the std::reverse algorithm: " << endl; 16 | cout << sampleStr << endl; 17 | 18 | return 0; 19 | } -------------------------------------------------------------------------------- /16.7 StringCaseConversion.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int main() 6 | { 7 | using namespace std; 8 | 9 | cout << "Please enter a string for case-conversion:" << endl; 10 | cout << "> "; 11 | 12 | string inStr; 13 | getline(cin, inStr); 14 | cout << endl; 15 | 16 | transform(inStr.begin(), inStr.end(), inStr.begin(), ::toupper); 17 | cout << "The string converted to upper case is: " << endl; 18 | cout << inStr << endl << endl; 19 | 20 | transform(inStr.begin(), inStr.end(), inStr.begin(), ::tolower); 21 | cout << "The string converted to lower case is: " << endl; 22 | cout << inStr << endl << endl; 23 | 24 | return 0; 25 | } -------------------------------------------------------------------------------- /16.8 StringLiteralsCPP14.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | string str1("Conventional string \0 initialization"); 8 | cout << "Str1: " << str1 << " Length: " << str1.length() << endl; 9 | 10 | string str2("Initialization \0 using literals"s); 11 | cout << "Str2: " << str2 << " Length: " << str2.length() << endl; 12 | 13 | return 0; 14 | } -------------------------------------------------------------------------------- /16.9 StringView.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | string strOriginal("Use views instead of copies of strings"); 8 | string_view fullView(strOriginal); // a full view 9 | 10 | cout << "The full view shows: " << fullView << endl; 11 | 12 | cout << "The first instance of 'v' is at position: " 13 | << fullView.find_first_of('v') << endl; 14 | 15 | cout << "Is view starting with \"Use\": " << \ 16 | (fullView.starts_with("Use") ? "true" : "false") << endl; // C++20 17 | 18 | cout << "Is view ending with \"strings\": " << \ 19 | (fullView.ends_with("strings") ? "true" : "false") << endl; // C++20 20 | 21 | string_view partialView(strOriginal.c_str(), 9); // partial view 22 | cout << "Partial view shows: " << partialView << endl; 23 | 24 | return 0; 25 | } -------------------------------------------------------------------------------- /16.Ex1 IsPalindrom.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int main() 6 | { 7 | using namespace std; 8 | 9 | cout << "Please enter a word for palindrome-check:" << endl; 10 | string strInput; 11 | cin >> strInput; 12 | 13 | string strCopy(strInput); 14 | reverse(strCopy.begin(), strCopy.end()); 15 | 16 | if (strCopy == strInput) 17 | cout << strInput << " is a palindrome!" << endl; 18 | else 19 | cout << strInput << " is not a palindrome." << endl; 20 | 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /16.Ex2 NumVowels.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | // Find the number of character 'chToFind' in string "strInput" 7 | int GetNumCharacters(string& strInput, char chToFind) 8 | { 9 | int nNumCharactersFound = 0; 10 | 11 | size_t nCharOffset = strInput.find(chToFind); 12 | while (nCharOffset != string::npos) 13 | { 14 | ++nNumCharactersFound; 15 | 16 | nCharOffset = strInput.find(chToFind, nCharOffset + 1); 17 | } 18 | 19 | return nNumCharactersFound; 20 | } 21 | 22 | int main() 23 | { 24 | 25 | cout << "Please enter a string:" << endl << "> "; 26 | string strInput; 27 | getline(cin, strInput); 28 | 29 | int nNumVowels = GetNumCharacters(strInput, 'a'); 30 | nNumVowels += GetNumCharacters(strInput, 'e'); 31 | nNumVowels += GetNumCharacters(strInput, 'i'); 32 | nNumVowels += GetNumCharacters(strInput, 'o'); 33 | nNumVowels += GetNumCharacters(strInput, 'u'); 34 | 35 | // DIY: handle capitals too.. 36 | 37 | cout << "The number of vowels in that sentence is:" << nNumVowels; 38 | 39 | return 0; 40 | } -------------------------------------------------------------------------------- /16.Ex3 AlternateCharUC.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int main() 6 | { 7 | using namespace std; 8 | 9 | cout << "Please enter a string for case-conversion:" << endl; 10 | cout << "> "; 11 | 12 | string strInput; 13 | getline(cin, strInput); 14 | cout << endl; 15 | 16 | for (size_t nCharIndex = 0 17 | ; nCharIndex < strInput.length() 18 | ; nCharIndex += 2) 19 | strInput[nCharIndex] = toupper(strInput[nCharIndex]); 20 | 21 | cout << "The string converted to upper case is: " << endl; 22 | cout << strInput << endl << endl; 23 | 24 | return 0; 25 | } -------------------------------------------------------------------------------- /16.Ex4 InsertSpacesInStr.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | using namespace std; 7 | 8 | const string str1 = "I"; 9 | const string str2 = "Love"; 10 | const string str3 = "STL"; 11 | const string str4 = "String."; 12 | 13 | string strResult = str1 + " " + str2 + " " + str3 + " " + str4; 14 | 15 | cout << "The sentence reads:" << endl; 16 | cout << strResult; 17 | 18 | return 0; 19 | } -------------------------------------------------------------------------------- /16.Ex5 FindCharA.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | using namespace std; 7 | 8 | string sampleStr("Good day String! Today is beautiful!"); 9 | cout << "Sample string is: " << sampleStr << endl; 10 | cout << "Locating all instances of character 'a'" << endl; 11 | 12 | auto charPos = sampleStr.find('a', 0); 13 | 14 | while (charPos != string::npos) 15 | { 16 | cout << "'" << 'a' << "' found"; 17 | cout << " at position: " << charPos << endl; 18 | 19 | // resume find starting with next character 20 | size_t charSearchPos = charPos + 1; 21 | 22 | charPos = sampleStr.find('a', charSearchPos); 23 | } 24 | 25 | return 0; 26 | } -------------------------------------------------------------------------------- /17.1 InstantiatingStdVector.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | // vector of integers 6 | std::vector integers; 7 | 8 | // vector with 3 elements initialized using list initialization 9 | std::vector initVector{ 202, 2017, -1 }; 10 | 11 | // Instantiate a vector with 10 elements(it can still grow) 12 | std::vector tenElements(10); 13 | 14 | // Instantiate a vector with 10 elements, each initialized to 90 15 | std::vector tenElemInit(10, 90); 16 | 17 | // Instantiate one vector and initialize it to the contents of another 18 | std::vector copyVector(tenElemInit); 19 | 20 | // Vector initialized to 5 elements from another using iterators 21 | std::vector partialCopy(tenElements.cbegin(), 22 | tenElements.cbegin() + 5); 23 | 24 | return 0; 25 | } -------------------------------------------------------------------------------- /17.2 InsertingPushBack.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | vector integers; 8 | 9 | // Insert sample integers into the vector: 10 | integers.push_back(50); 11 | integers.push_back(1); 12 | integers.push_back(987); 13 | integers.push_back(1001); 14 | 15 | cout << "The vector contains "; 16 | cout << integers.size() << " Elements" << endl; 17 | 18 | return 0; 19 | } -------------------------------------------------------------------------------- /17.3 VectorInsert.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | void DisplayVector(const vector& inVec) 6 | { 7 | for(auto element = inVec.cbegin(); // auto and cbegin() are C++11 8 | element != inVec.cend(); // cend() is new in C++11 9 | ++ element) 10 | cout << *element << ' '; 11 | 12 | cout << endl; 13 | } 14 | 15 | int main() 16 | { 17 | // Instantiate a vector with 4 elements, each initialized to 90 18 | vector integers(4, 90); 19 | 20 | cout << "The initial contents of the vector: "; 21 | DisplayVector(integers); 22 | 23 | // Insert 25 at the beginning 24 | integers.insert(integers.begin(), 25); 25 | 26 | // Insert 2 numbers of value 45 at the end 27 | integers.insert(integers.end(), 2, 45); 28 | 29 | cout << "Vector after inserting elements at beginning and end: "; 30 | DisplayVector(integers); 31 | 32 | // Another vector containing 2 elements of value 30 33 | vector vecAnother(2, 30); 34 | 35 | // Insert two elements from another container in position [1] 36 | integers.insert(integers.begin() + 1, 37 | vecAnother.begin(), vecAnother.end()); 38 | 39 | cout << "Vector after inserting contents from another vector: "; 40 | cout << "in the middle:" << endl; 41 | DisplayVector(integers); 42 | 43 | return 0; 44 | } -------------------------------------------------------------------------------- /17.4 VectorElementAccessArray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | using namespace std; 7 | vector integers{ 50, 1, 987, 1001 }; 8 | 9 | for(size_t index = 0; index < integers.size(); ++index) 10 | { 11 | cout << "Element[" << index << "] = " ; 12 | cout << integers[index] << endl; 13 | } 14 | 15 | integers[2] = 2011; // change value of 3rd element 16 | cout << "After replacement: " << endl; 17 | cout << "Element[2] = " << integers[2] << endl; 18 | 19 | return 0; 20 | } -------------------------------------------------------------------------------- /17.5 VectorPointerSemantics.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | using namespace std; 7 | vector integers{ 50, 1, 987, 1001 }; 8 | 9 | vector::const_iterator element = integers.cbegin(); 10 | // auto element = integers.cbegin(); // same as above, using auto 11 | 12 | while(element != integers.end()) 13 | { 14 | size_t index = distance(integers.cbegin(), element); 15 | 16 | cout << "Element at position "; 17 | cout << index << " is: " << *element << endl; 18 | 19 | // move to the next element 20 | ++ element; 21 | } 22 | 23 | return 0; 24 | } -------------------------------------------------------------------------------- /17.6 VectorPopBack.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | template 6 | void DisplayVector(const vector& inVec) 7 | { 8 | for(const auto& element : inVec) 9 | cout << element << ' '; 10 | 11 | cout << endl; 12 | } 13 | 14 | int main() 15 | { 16 | vector integers; 17 | 18 | // Insert sample integers into the vector: 19 | integers.push_back(50); 20 | integers.push_back(1); 21 | integers.push_back(987); 22 | integers.push_back(1001); 23 | 24 | cout << "Vector contains " << integers.size() << " elements: "; 25 | DisplayVector(integers); 26 | 27 | // Erase one element at the end 28 | integers.pop_back(); 29 | 30 | cout << "After a call to pop_back()" << endl; 31 | cout << "Vector contains " << integers.size() << " elements: "; 32 | DisplayVector(integers); 33 | 34 | return 0; 35 | } -------------------------------------------------------------------------------- /17.7 SizeCapacity.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | using namespace std; 7 | 8 | // Instantiate a vector object that holds 5 integers of default value 9 | vector integers(5); 10 | 11 | cout << "Vector of integers was instantiated with " << endl; 12 | cout << "Size: " << integers.size(); 13 | cout << ", Capacity: " << integers.capacity() << endl; 14 | 15 | // Inserting a 6th element in to the vector 16 | integers.push_back(666); 17 | 18 | cout << "After inserting an additional element... " << endl; 19 | cout << "Size: " << integers.size(); 20 | cout << ", Capacity: " << integers.capacity() << endl; 21 | 22 | // Inserting another element 23 | integers.push_back(777); 24 | 25 | cout << "After inserting yet another element... " << endl; 26 | cout << "Size: " << integers.size(); 27 | cout << ", Capacity: " << integers.capacity() << endl; 28 | 29 | return 0; 30 | } -------------------------------------------------------------------------------- /17.Ex4 DequeListInit.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | template 7 | void DisplayDeque(deque inDQ) 8 | { 9 | for (auto element = inDQ.cbegin(); 10 | element != inDQ.cend(); 11 | ++element) 12 | cout << *element << endl; 13 | } 14 | 15 | int main() 16 | { 17 | deque strDq{ "Hello"s, "Containers are cool"s, 18 | "C++ is evolving!"s }; 19 | DisplayDeque(strDq); 20 | 21 | return 0; 22 | } -------------------------------------------------------------------------------- /18.1 InstantiatingList.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | using namespace std; 7 | 8 | // instantiate an empty list 9 | list listIntegers; 10 | 11 | // instantiate a list with 10 integers 12 | list listWith10Integers(10); 13 | 14 | // instantiate a list with 4 integers, each initialized to 99 15 | list listWith4IntegerEach99(4, 99); 16 | 17 | // create an exact copy of an existing list 18 | list listCopyAnother(listWith4IntegerEach99); 19 | 20 | // a vector with 10 integers, each 2017 21 | vector vecIntegers(10, 2017); 22 | 23 | // instantiate a list using values from another container 24 | list listContainsCopyOfAnother(vecIntegers.cbegin(), 25 | vecIntegers.cend()); 26 | 27 | return 0; 28 | } -------------------------------------------------------------------------------- /18.2 InsertingFrontEnd.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | template 6 | void DisplayContents(const T& container) 7 | { 8 | for(auto element = container.cbegin(); 9 | element != container.cend(); 10 | ++ element ) 11 | cout << *element << ' '; 12 | 13 | cout << endl; 14 | } 15 | 16 | int main() 17 | { 18 | std::list linkInts{ -101, 42 }; 19 | 20 | linkInts.push_front(10); 21 | linkInts.push_front(2011); 22 | linkInts.push_back(-1); 23 | linkInts.push_back(9999); 24 | 25 | DisplayContents(linkInts); 26 | 27 | return 0; 28 | } 29 | 30 | 31 | /* 32 | // for non-C++11 compliant compilers 33 | template 34 | void DisplayContents(const T& Input) 35 | { 36 | for(T::const_iterator iElement = Input.begin() 37 | ; iElement != Input.end() 38 | ; ++ iElement ) 39 | cout << *iElement << ' '; 40 | 41 | cout << endl; 42 | } 43 | */ 44 | 45 | -------------------------------------------------------------------------------- /18.4 ListErase.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | template 6 | void DisplayContents(const T& container) 7 | { 8 | for(auto element = container.cbegin(); 9 | element != container.cend(); 10 | ++ element ) 11 | cout << *element << ' '; 12 | 13 | cout << endl; 14 | } 15 | 16 | int main() 17 | { 18 | std::list linkInts{ 4, 3, 5, -1, 2017 }; 19 | 20 | // Store an iterator obtained in using insert() 21 | auto iValue2 = linkInts.insert(linkInts.begin(), 2); 22 | 23 | cout << "Initial contents of the list:" << endl; 24 | DisplayContents(linkInts); 25 | 26 | cout << "After erasing element '"<< *iValue2 << "':" << endl; 27 | linkInts.erase(iValue2); 28 | DisplayContents(linkInts); 29 | 30 | linkInts.erase(linkInts.begin(), linkInts.end()); 31 | cout << "Number of elements after erasing range: "; 32 | cout << linkInts.size() << endl; 33 | 34 | linkInts.clear(); 35 | 36 | return 0; 37 | } -------------------------------------------------------------------------------- /18.5 ListReverse.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | template 6 | void DisplayContents(const T& container) 7 | { 8 | for(auto element = container.cbegin(); 9 | element != container.cend(); 10 | ++ element ) 11 | cout << *element << ' '; 12 | 13 | cout << endl; 14 | } 15 | 16 | int main() 17 | { 18 | std::list linkInts{ 0, 1, 2, 3, 4, 5 }; 19 | 20 | cout << "Initial contents of the list:" << endl; 21 | DisplayContents(linkInts); 22 | 23 | linkInts.reverse(); 24 | 25 | cout << "Contents of the list after using reverse():" << endl; 26 | DisplayContents(linkInts); 27 | 28 | return 0; 29 | } -------------------------------------------------------------------------------- /18.6 ListSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | bool SortPredicate_Descending(const int& lsh, const int& rsh) 6 | { 7 | // define criteria for list::sort: return true for desired order 8 | return(lsh > rsh); 9 | } 10 | 11 | template 12 | void DisplayContents(const T& container) 13 | { 14 | for(auto element = container.cbegin(); 15 | element != container.cend(); 16 | ++ element ) 17 | cout << *element << ' '; 18 | 19 | cout << endl; 20 | } 21 | 22 | int main() 23 | { 24 | list linkInts{ 0, -1, 2011, 444, -5 }; 25 | 26 | cout << "Initial contents of the list are - " << endl; 27 | DisplayContents(linkInts); 28 | 29 | linkInts.sort(); 30 | 31 | cout << "Order after sort():" << endl; 32 | DisplayContents(linkInts); 33 | 34 | linkInts.sort(SortPredicate_Descending); 35 | cout << "Order after sort() with a predicate:" << endl; 36 | DisplayContents(linkInts); 37 | 38 | return 0; 39 | } -------------------------------------------------------------------------------- /18.8 ForwardList.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | template 6 | void DisplayContents(const T& container) 7 | { 8 | for(auto element = container.cbegin(); 9 | element != container.cend(); 10 | ++ element ) 11 | cout << *element << ' '; 12 | 13 | cout << endl; 14 | } 15 | 16 | int main() 17 | { 18 | forward_list flistIntegers{ 3, 4, 2, 2, 0 }; 19 | flistIntegers.push_front(1); 20 | 21 | cout << "Contents of forward_list: " << endl; 22 | DisplayContents(flistIntegers); 23 | 24 | flistIntegers.remove(2); 25 | flistIntegers.sort(); 26 | cout << "Contents after removing 2 and sorting: " << endl; 27 | DisplayContents(flistIntegers); 28 | 29 | return 0; 30 | } -------------------------------------------------------------------------------- /18.Ex3 InsertVecInList.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() 8 | { 9 | vector vecData{ 0, 10, 20, 30 }; 10 | 11 | list linkInts; 12 | 13 | // Insert contents of vector into beginning of list 14 | linkInts.insert(linkInts.begin(), 15 | vecData.begin(), vecData.end()); 16 | 17 | cout << "The contents of the list are: "; 18 | 19 | list::const_iterator element; 20 | for(element = linkInts.begin(); 21 | element != linkInts.end(); 22 | ++element) 23 | cout << *element << " "; 24 | 25 | return 0; 26 | } -------------------------------------------------------------------------------- /18.Ex4 ListStrings.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() 8 | { 9 | list names; 10 | names.push_back("Jack"); 11 | names.push_back("John"); 12 | names.push_back("Anna"); 13 | names.push_back("Skate"); 14 | 15 | cout << "The contents of the list are: "; 16 | 17 | list ::const_iterator element; 18 | for(element = names.begin(); element != names.end(); ++element) 19 | cout << *element << " "; 20 | cout << endl; 21 | 22 | cout << "The contents after reversing are: "; 23 | names.reverse(); 24 | for(element = names.begin(); element != names.end(); ++element) 25 | cout << *element << " "; 26 | cout << endl; 27 | 28 | cout << "The contents after sorting are: "; 29 | names.sort(); 30 | for(element = names.begin(); element != names.end(); ++element) 31 | cout << *element << " "; 32 | cout << endl; 33 | 34 | return 0; 35 | } -------------------------------------------------------------------------------- /19.1 InstantiatingSetMSet.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // used as a template parameter in set / multiset instantiation 4 | template 5 | struct SortDescending 6 | { 7 | bool operator()(const T& lhs, const T& rhs) const 8 | { 9 | return(lhs > rhs); 10 | } 11 | }; 12 | 13 | int main() 14 | { 15 | using namespace std; 16 | 17 | // a simple set or multiset of integers(using default sort predicate) 18 | set setInts1; 19 | multiset msetInts1; 20 | 21 | // set and multiset instantiated given a user-defined sort predicate 22 | set > setInts2; 23 | multiset > msetInts2; 24 | 25 | // creating one set from another, or part of another container 26 | set setInts3(setInts1); 27 | multiset msetInts3(setInts1.cbegin(), setInts1.cend()); 28 | 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /19.2 InsertSetMSet.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | template 6 | void DisplayContents(const T& container) 7 | { 8 | for(auto element = container.cbegin(); 9 | element != container.cend(); 10 | ++element) 11 | cout << *element << ' '; 12 | 13 | cout << endl; 14 | } 15 | 16 | int main() 17 | { 18 | set setInts{ 202, 151, -999, -1 }; 19 | setInts.insert(-1); // duplicate 20 | cout << "Contents of the set: " << endl; 21 | DisplayContents(setInts); 22 | 23 | multiset msetInts; 24 | msetInts.insert(setInts.begin(), setInts.end()); 25 | msetInts.insert(-1); // duplicate 26 | 27 | cout << "Contents of the multiset: " << endl; 28 | DisplayContents(msetInts); 29 | 30 | cout << "Number of instances of '-1' in the multiset are: '"; 31 | cout << msetInts.count(-1) << "'" << endl; 32 | 33 | return 0; 34 | } -------------------------------------------------------------------------------- /19.3 SetFind.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | set setInts{ 43, 78, -1, 124 }; 8 | 9 | // Display contents of the set to the screen 10 | for(auto element = setInts.cbegin(); 11 | element != setInts.cend(); 12 | ++ element) 13 | cout << *element << endl; 14 | 15 | // Try finding an element 16 | auto elementFound = setInts.find(-1); 17 | 18 | // Check if found... 19 | if(elementFound != setInts.end()) 20 | cout << "Element " << *elementFound << " found!" << endl; 21 | else 22 | cout << "Element not found in set!" << endl; 23 | 24 | // finding another 25 | auto anotherFind = setInts.find(12345); 26 | 27 | // Check if found... 28 | if(anotherFind != setInts.end()) 29 | cout << "Element " << *anotherFind << " found!" << endl; 30 | else 31 | cout << "Element 12345 not found in set!" << endl; 32 | 33 | return 0; 34 | } -------------------------------------------------------------------------------- /19.4 MSetErase.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | template 6 | void DisplayContents(const T& Input) 7 | { 8 | for(auto element = Input.cbegin(); 9 | element != Input.cend(); 10 | ++ element) 11 | cout << *element << ' '; 12 | 13 | cout << endl; 14 | } 15 | 16 | typedef multiset MSETINT; 17 | 18 | int main() 19 | { 20 | MSETINT msetInts{ 43, 78, 78, -1, 124 }; 21 | 22 | cout << "multiset contains " << msetInts.size() << " elements: "; 23 | DisplayContents(msetInts); 24 | 25 | cout << "Enter a number to erase from the set: "; 26 | int input = 0; 27 | cin >> input; 28 | 29 | cout << "Erasing " << msetInts.count(input); 30 | cout << " instances of value " << input << endl; 31 | 32 | msetInts.erase(input); 33 | 34 | cout << "multiset now contains " << msetInts.size() << " elements: "; 35 | DisplayContents(msetInts); 36 | 37 | return 0; 38 | } -------------------------------------------------------------------------------- /19.6 UnorderedSet.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | template 6 | void DisplayContents(const T& cont) 7 | { 8 | cout << "Unordered set contains: "; 9 | for(auto element = cont.cbegin(); 10 | element != cont.cend(); 11 | ++ element) 12 | cout<< *element << ' '; 13 | 14 | cout << endl; 15 | 16 | cout << "Number of elements, size() = " << cont.size() << endl; 17 | cout << "Bucket count = " << cont.bucket_count() << endl; 18 | cout << "Max load factor = " << cont.max_load_factor() << endl; 19 | cout << "Load factor: " << cont.load_factor() << endl << endl; 20 | } 21 | 22 | int main() 23 | { 24 | unordered_set usetInt{ 1, -3, 2017, 300, -1, 989, -300, 9 }; 25 | DisplayContents(usetInt); 26 | usetInt.insert(999); 27 | DisplayContents(usetInt); 28 | 29 | cout << "Enter int you want to check for existence in set: "; 30 | int input = 0; 31 | cin >> input; 32 | auto elementFound = usetInt.find(input); 33 | 34 | if(elementFound != usetInt.end()) 35 | cout << *elementFound << " found in set" << endl; 36 | else 37 | cout << input << " not available in set" << endl; 38 | 39 | return 0; 40 | } -------------------------------------------------------------------------------- /19.Ex2 WordAndMeaning.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | struct PAIR_WORD_MEANING 8 | { 9 | string word; 10 | string meaning; 11 | 12 | PAIR_WORD_MEANING(const string& sWord, const string& sMeaning) 13 | : word(sWord), meaning(sMeaning) {} 14 | 15 | bool operator<(const PAIR_WORD_MEANING& pairAnotherWord) const 16 | { 17 | return(word < pairAnotherWord.word); 18 | } 19 | 20 | bool operator==(const string& key) 21 | { 22 | return(key == this->word); 23 | } 24 | }; 25 | 26 | int main() 27 | { 28 | multiset msetDictionary; 29 | PAIR_WORD_MEANING word1("C++", "A programming language"); 30 | PAIR_WORD_MEANING word2("Programmer", "A geek!"); 31 | 32 | msetDictionary.insert(word1); 33 | msetDictionary.insert(word2); 34 | 35 | cout << "Enter a word you wish to find the meaning of" << endl; 36 | string input; 37 | getline(cin, input); 38 | auto element = msetDictionary.find(PAIR_WORD_MEANING(input, "")); 39 | if(element != msetDictionary.end()) 40 | cout << "Meaning is: " <<(*element).meaning << endl; 41 | 42 | return 0; 43 | } -------------------------------------------------------------------------------- /19.Ex3 SetMSetCompare.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | template 7 | void DisplayContent(const T& cont) 8 | { 9 | for(auto element = cont.cbegin(); element != cont.cend(); ++element) 10 | cout << *element << " "; 11 | } 12 | 13 | int main() 14 | { 15 | multiset msetIntegers; 16 | 17 | msetIntegers.insert(5); 18 | msetIntegers.insert(5); 19 | msetIntegers.insert(5); 20 | 21 | set setIntegers; 22 | setIntegers.insert(5); 23 | setIntegers.insert(5); 24 | setIntegers.insert(5); 25 | 26 | cout << "Displaying the contents of the multiset: "; 27 | DisplayContent(msetIntegers); 28 | cout << endl; 29 | 30 | cout << "Displaying the contents of the set: "; 31 | DisplayContent(setIntegers); 32 | cout << endl; 33 | 34 | return 0; 35 | } -------------------------------------------------------------------------------- /2.1 HelloWorldAnalysis.cpp: -------------------------------------------------------------------------------- 1 | // Preprocessor directive that includes header iostream 2 | #include 3 | 4 | // Start of your program: function block main() 5 | int main() 6 | { 7 | /* Write to the console output i.e. screen */ 8 | std::cout << "Hello World" << std::endl; 9 | 10 | // Return a value to the OS 11 | return 0; 12 | } 13 | -------------------------------------------------------------------------------- /2.2 UsingNamespaceDecl.cpp: -------------------------------------------------------------------------------- 1 | // Pre-processor directive 2 | #include 3 | 4 | // Start of your program 5 | int main() 6 | { 7 | // Tell the compiler what namespace to look in 8 | using namespace std; 9 | 10 | /* Write to the screen using cout */ 11 | cout << "Hello World" << endl; 12 | 13 | // Return a value to the OS 14 | return 0; 15 | } -------------------------------------------------------------------------------- /2.3 UsingRestricted.cpp: -------------------------------------------------------------------------------- 1 | // Preprocessor directive 2 | #include 3 | 4 | // Start of your program 5 | int main() 6 | { 7 | using std::cout; 8 | using std::endl; 9 | 10 | /* Write to the screen using cout */ 11 | cout << "Hello World" << endl; 12 | 13 | // Return a value to the OS 14 | return 0; 15 | } -------------------------------------------------------------------------------- /2.4 FirstFunction_Demo_cout.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Function declaration 5 | int DemoConsoleOutput(); 6 | 7 | int main() 8 | { 9 | // Function call 10 | DemoConsoleOutput(); 11 | 12 | return 0; 13 | } 14 | 15 | // Function definition 16 | int DemoConsoleOutput() 17 | { 18 | cout << "This is a simple string literal" << endl; 19 | cout << "Writing number five: " << 5 << endl; 20 | cout << "Performing division 10 / 5 = " << 10 / 5 << endl; 21 | cout << "Pi is 22 / 7 = " << 22.0 / 7 << endl; 22 | 23 | return 0; 24 | } -------------------------------------------------------------------------------- /2.5 FunctionValueReturnedFromMain.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Function declaration and definition 5 | int DemoConsoleOutput() 6 | { 7 | cout << "This is a simple string literal" << endl; 8 | cout << "Writing number five: " << 5 << endl; 9 | cout << "Performing division 10 / 5 = " << 10 / 5 << endl; 10 | cout << "Pi is 22 / 7 = " << 22.0 / 7 << endl; 11 | 12 | return 0; 13 | } 14 | 15 | int main() 16 | { 17 | // Function call with return used to exit 18 | return DemoConsoleOutput(); 19 | } -------------------------------------------------------------------------------- /2.6 Anatomy_BasicIO.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | // Declare a variable to store an integer 8 | int inputNumber; 9 | 10 | cout << "Enter an integer: "; 11 | 12 | // store integer given user input 13 | cin >> inputNumber; 14 | 15 | // The same with text i.e. string data 16 | cout << "Enter your name: "; 17 | string inputName; 18 | cin >> inputName; 19 | 20 | cout << inputName << " entered " << inputNumber << endl; 21 | 22 | return 0; 23 | } -------------------------------------------------------------------------------- /2.Ex2.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/learncppnow/9E/97b254e0eb394ab67553d9f4f61736714c884af0/2.Ex2.cpp -------------------------------------------------------------------------------- /2.Ex3.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Function declaration 5 | int DemoConsoleOutput(); 6 | 7 | int main() 8 | { 9 | // Call i.e. invoke the function 10 | DemoConsoleOutput(); 11 | 12 | return 0; 13 | } 14 | 15 | // Function definition 16 | int DemoConsoleOutput() 17 | { 18 | cout << "10 - 5 = " << 10 - 5 << endl; 19 | cout << "10 * 5 = " << 10 * 5 << endl; 20 | 21 | return 0; 22 | } 23 | 24 | -------------------------------------------------------------------------------- /20.1 InstantiatingMapMultimap.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | template 5 | struct ReverseSort 6 | { 7 | bool operator()(const keyType& key1, const keyType& key2) const 8 | { 9 | return(key1 > key2); 10 | } 11 | }; 12 | 13 | int main() 14 | { 15 | using namespace std; 16 | 17 | // map and multimap key of type int to value of type string 18 | map mapIntToStr1; 19 | multimap mmapIntToStr1; 20 | 21 | // map and multimap constructed as a copy of another 22 | map mapIntToStr2(mapIntToStr1); 23 | multimap mmapIntToStr2(mmapIntToStr1); 24 | 25 | // map and multimap constructed given a part of another map or multimap 26 | map mapIntToStr3(mapIntToStr1.cbegin(), 27 | mapIntToStr1.cend()); 28 | 29 | multimap mmapIntToStr3(mmapIntToStr1.cbegin(), 30 | mmapIntToStr1.cend()); 31 | 32 | // map and multimap with a predicate that inverses sort order 33 | map > mapIntToStr4 34 | (mapIntToStr1.cbegin(), mapIntToStr1.cend()); 35 | 36 | multimap > mmapIntToStr4 37 | (mapIntToStr1.cbegin(), mapIntToStr1.cend()); 38 | 39 | return 0; 40 | } -------------------------------------------------------------------------------- /20.3 MapFind.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | template 7 | void DisplayContents(const T& cont) 8 | { 9 | for(auto element = cont.cbegin(); 10 | element != cont.cend(); 11 | ++ element) 12 | cout << element->first << " -> " << element->second << endl; 13 | 14 | cout << endl; 15 | } 16 | 17 | int main() 18 | { 19 | map mapIntToStr; 20 | 21 | mapIntToStr.insert(make_pair(3, "Three")); 22 | mapIntToStr.insert(make_pair(45, "Forty Five")); 23 | mapIntToStr.insert(make_pair(-1, "Minus One")); 24 | mapIntToStr.insert(make_pair(1000, "Thousand")); 25 | 26 | cout << "The multimap contains " << mapIntToStr.size(); 27 | cout << " key-value pairs. They are: " << endl; 28 | 29 | // Print the contents of the map to the screen 30 | DisplayContents(mapIntToStr); 31 | 32 | cout << "Enter the key you wish to find: "; 33 | int key = 0; 34 | cin >> key; 35 | 36 | auto pairFound = mapIntToStr.find(key); 37 | if(pairFound != mapIntToStr.end()) 38 | { 39 | cout << "Key " << pairFound->first << " points to Value: "; 40 | cout << pairFound->second << endl; 41 | } 42 | else 43 | cout << "Sorry, pair with key " << key << " not in map\n"; 44 | 45 | return 0; 46 | } -------------------------------------------------------------------------------- /21.1 FunctionObjects.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | // A unary function 8 | template 9 | void FuncDisplayElement(const elementType& element) 10 | { 11 | cout << element << ' '; 12 | }; 13 | 14 | // struct that behaves as a unary function 15 | template 16 | struct DisplayElement 17 | { 18 | void operator()(const elementType& element) const 19 | { 20 | cout << element << ' '; 21 | } 22 | }; 23 | 24 | int main() 25 | { 26 | vector numsInVec{ 0, 1, 2, 3, -1, -9, 0, -999 }; 27 | cout << "Vector of integers contains: " << endl; 28 | 29 | for_each(numsInVec.begin(), // Start of range 30 | numsInVec.end(), // End of range 31 | DisplayElement() ); // Unary function object 32 | 33 | // Display the list of characters 34 | list charsInList{ 'a', 'z', 'k', 'd' }; 35 | cout << endl << "List of characters contains: " << endl; 36 | 37 | for_each(charsInList.begin(), 38 | charsInList.end(), 39 | FuncDisplayElement); 40 | 41 | return 0; 42 | } -------------------------------------------------------------------------------- /21.2 StatefulFunctionObject.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | template 7 | struct DisplayElementKeepCount 8 | { 9 | int count; 10 | DisplayElementKeepCount() : count(0) {} // constructor 11 | 12 | void operator()(const elementType& element) 13 | { 14 | ++ count; 15 | cout << element<< ' '; 16 | } 17 | }; 18 | 19 | int main() 20 | { 21 | vector numsInVec{ 22, 2017, -1, 999, 43, 901 }; 22 | cout << "Displaying the vector of integers: "<< endl; 23 | 24 | DisplayElementKeepCount result; 25 | result = for_each(numsInVec.begin(), 26 | numsInVec.end(), 27 | DisplayElementKeepCount() ); 28 | 29 | cout << endl << "Functor invoked " << result.count << " times"; 30 | 31 | return 0; 32 | } -------------------------------------------------------------------------------- /21.3 21.4 UsingUnaryPredicate.cpp: -------------------------------------------------------------------------------- 1 | // A structure as a unary predicate 2 | template 3 | struct IsMultiple 4 | { 5 | numberType Divisor; 6 | 7 | IsMultiple(const numberType& divisor) 8 | { 9 | Divisor = divisor; 10 | } 11 | 12 | bool operator()(const numberType& element) const 13 | { 14 | // Check if the dividend is a multiple of the divisor 15 | return((element % Divisor) == 0); 16 | } 17 | }; 18 | 19 | #include 20 | #include 21 | #include 22 | using namespace std; 23 | 24 | int main() 25 | { 26 | vector numsInVec{ 25, 26, 27, 28, 29, 30, 31 }; 27 | cout << "The vector contains: 25, 26, 27, 28, 29, 30, 31" << endl; 28 | 29 | cout << "Enter divisor(> 0): "; 30 | int divisor = 2; 31 | cin >> divisor; 32 | 33 | // Find the first element that is a multiple of 4 in the collection 34 | auto element = find_if(numsInVec.begin(), 35 | numsInVec.end(), 36 | IsMultiple(divisor) ); 37 | 38 | if(element != numsInVec.end()) 39 | { 40 | cout << "First element in vector divisible by " << divisor; 41 | cout << ": " << *element << endl; 42 | } 43 | 44 | return 0; 45 | } -------------------------------------------------------------------------------- /21.8 LambdaDisplayContainerForEach.cpp: -------------------------------------------------------------------------------- 1 | // this has been moved to Chapter 22, Listing 22.1 2 | 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | using namespace std; 10 | 11 | int main() 12 | { 13 | vector vecIntegers; 14 | 15 | for(int nCount = 0; nCount < 10; ++ nCount) 16 | vecIntegers.push_back(nCount); 17 | 18 | list listChars; 19 | for(char nChar = 'a'; nChar < 'k'; ++nChar) 20 | listChars.push_back(nChar); 21 | 22 | cout << "Displaying the vector of integers: " << endl; 23 | 24 | // Display the array of integers 25 | for_each( vecIntegers.begin() // Start of range 26 | , vecIntegers.end() // End of range 27 | , [](int Num) {cout << Num << ' '; } ); // Unary function object 28 | 29 | cout << endl << endl; 30 | cout << "Displaying the list of characters: " << endl; 31 | 32 | // Display the list of characters 33 | for_each( listChars.begin() // Start of range 34 | , listChars.end() // End of range 35 | , [](int Num) {cout << Num << ' '; } );// Unary function object 36 | 37 | cout << endl; 38 | 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /21.Ex1 DoubleElement.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | template 7 | struct Double 8 | { 9 | void operator()(const elementType element) const 10 | { 11 | cout << element * 2 << ' '; 12 | } 13 | }; 14 | 15 | int main() 16 | { 17 | vector numsInVec; 18 | 19 | for(int count = 0; count < 10; ++count) 20 | numsInVec.push_back(count); 21 | 22 | cout << "Displaying the vector of integers: " << endl; 23 | 24 | // Display the array of integers 25 | for_each(numsInVec.begin(), // Start of range 26 | numsInVec.end(), // End of range 27 | Double<>()); // Unary function object 28 | 29 | return 0; 30 | } -------------------------------------------------------------------------------- /21.Ex2 DoubleKeepCount.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | template 7 | struct Double 8 | { 9 | int count = 0; 10 | void operator()(const elementType element) 11 | { 12 | ++count; 13 | cout << element * 2 << ' '; 14 | } 15 | }; 16 | 17 | int main() 18 | { 19 | vector numsInVec; 20 | 21 | for(int count = 0; count < 10; ++count) 22 | numsInVec.push_back(count); 23 | 24 | cout << "Displaying the vector of integers: " << endl; 25 | 26 | Double doubleElement; 27 | // Display the array of integers 28 | doubleElement = for_each(numsInVec.begin(), // Start of range 29 | numsInVec.end(), // End of range 30 | Double<>()); // Unary function object 31 | 32 | cout << "\nFunctor called: " << doubleElement.count << " times\n"; 33 | 34 | return 0; 35 | } -------------------------------------------------------------------------------- /21.Ex3 BinaryPredSort.cpp: -------------------------------------------------------------------------------- 1 | template 2 | class SortAscending 3 | { 4 | public: 5 | bool operator()(const elementType& num1, 6 | const elementType& num2) const 7 | { 8 | return(num1 < num2); 9 | } 10 | }; 11 | 12 | #include 13 | #include 14 | #include 15 | 16 | int main() 17 | { 18 | std::vector numsInVec; 19 | 20 | // Insert sample numbers: 100, 90... 20, 10 21 | for(int sample = 10; sample > 0; --sample) 22 | numsInVec.push_back(sample * 10); 23 | 24 | std::sort(numsInVec.begin(), numsInVec.end(), 25 | SortAscending()); 26 | 27 | for(size_t index = 0; index < numsInVec.size(); ++index) 28 | std::cout << numsInVec[index] << ' '; 29 | 30 | return 0; 31 | } -------------------------------------------------------------------------------- /22.1 LambdaDisplayElements.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | int main() 8 | { 9 | vector numsInVec{ 101, -4, 500, 21, 42, -1 }; 10 | cout << "Display elements in a vector using a lambda: " << endl; 11 | 12 | // Display the array of integers 13 | for_each(numsInVec.cbegin(), // Start of range 14 | numsInVec.cend(), // End of range 15 | [](const int& element) {cout << element << ' '; }); // lambda 16 | 17 | cout << endl; 18 | 19 | list charsInList{ 'a', 'h', 'z', 'k', 'l' }; 20 | cout << "Display elements in a list using a lambda: " << endl; 21 | 22 | // Display the list of characters 23 | for_each(charsInList.cbegin(), // Start of range 24 | charsInList.cend(), // End of range 25 | [](auto& element) {cout << element << ' '; }); // lambda 26 | 27 | return 0; 28 | } -------------------------------------------------------------------------------- /22.2 LambdaFindIfEvenNumbers.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | vector numsInVec{ 25, 101, 2017, -50 }; 9 | 10 | auto evenNum = find_if(numsInVec.cbegin(), 11 | numsInVec.cend(), // range to find in 12 | [](const int& num){return((num % 2) == 0); }); 13 | 14 | if(evenNum != numsInVec.cend()) 15 | cout << "Even number in collection is: " << *evenNum << endl; 16 | 17 | return 0; 18 | } -------------------------------------------------------------------------------- /22.3 LambdaVersionIsMultiple.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | vector numsInVec{25, 26, 27, 28, 29, 30, 31}; 9 | cout << "The vector contains: {25, 26, 27, 28, 29, 30, 31}"; 10 | 11 | cout << endl << "Enter divisor(> 0): "; 12 | int divisor = 2; 13 | cin >> divisor; 14 | 15 | // Find the first element that is a multiple of divisor 16 | vector::iterator element; 17 | element = find_if(numsInVec.begin(), 18 | numsInVec.end(), 19 | [divisor](int dividend){return(dividend % divisor) == 0; }); 20 | 21 | if(element != numsInVec.end()) 22 | { 23 | cout << "First element in vector divisible by " << divisor; 24 | cout << ": " << *element << endl; 25 | } 26 | 27 | return 0; 28 | } -------------------------------------------------------------------------------- /22.4 LambdaBinaryFunc.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int main() 6 | { 7 | using namespace std; 8 | 9 | vector vecMultiplicand{ 0, 1, 2, 3, 4 }; 10 | vector vecMultiplier{ 100, 101, 102, 103, 104 }; 11 | 12 | // Holds the result of multiplication 13 | vector vecResult; 14 | 15 | // Make space for the result of the multiplication 16 | vecResult.resize(vecMultiplier.size()); 17 | 18 | transform(vecMultiplicand.begin(), // range of multiplicands 19 | vecMultiplicand.end(), // end of range 20 | vecMultiplier.begin(), // multiplier values 21 | vecResult.begin(), // range that holds result 22 | [](int a, int b) {return a * b; }); // lambda 23 | 24 | cout << "The contents of the first vector are: " << endl; 25 | for(size_t index = 0; index < vecMultiplicand.size(); ++index) 26 | cout << vecMultiplicand[index] << ' '; 27 | cout << endl; 28 | 29 | cout << "The contents of the second vector are: " << endl; 30 | for(size_t index = 0; index < vecMultiplier.size(); ++index) 31 | cout << vecMultiplier[index] << ' '; 32 | cout << endl; 33 | 34 | cout << "The result of the multiplication is: " << endl; 35 | for(size_t index = 0; index < vecResult.size(); ++index) 36 | cout << vecResult[index] << ' '; 37 | 38 | return 0; 39 | } -------------------------------------------------------------------------------- /22.Ex1 LambdaSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | vector vecNumbers{25, -5, 122, 2021, -10001}; 9 | 10 | // template lambda that displays element on screen 11 | auto displayElement = [](const T& element) 12 | { cout << element << ' ';}; 13 | 14 | cout << "Elements in vector in initial order:\n"; 15 | for_each(vecNumbers.cbegin(), vecNumbers.cend(), displayElement); 16 | 17 | sort(vecNumbers.begin(), vecNumbers.end()); 18 | 19 | cout << "\nAfter sort using default predicate:\n"; 20 | for_each(vecNumbers.cbegin(), vecNumbers.cend(), displayElement); 21 | 22 | sort(vecNumbers.begin(), vecNumbers.end(), 23 | [](auto& lhs, auto& rhs) {return(lhs > rhs); }); 24 | 25 | cout << "\nAfter sort in descending order:\n"; 26 | for_each(vecNumbers.cbegin(), vecNumbers.cend(), displayElement); 27 | 28 | return 0; 29 | } -------------------------------------------------------------------------------- /22.Ex2 LambdAddsNum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | vector vecNumbers{25, -5, 122, 2021, -10001}; 9 | 10 | // template lambda that displays element on screen 11 | auto displayElement = [](const T& element) 12 | { cout << element << ' ';}; 13 | 14 | cout << "Elements in vector in initial order:\n"; 15 | for_each(vecNumbers.cbegin(), vecNumbers.cend(), displayElement); 16 | 17 | cout << "\nEnter number to add to all elements: "; 18 | int num = 0; 19 | cin >> num; 20 | 21 | for_each(vecNumbers.begin(), vecNumbers.end(), 22 | [=](int& element) {element += num; }); 23 | 24 | cout << "\nElements after adding the supplied number:\n"; 25 | for_each(vecNumbers.cbegin(), vecNumbers.cend(), displayElement); 26 | 27 | return 0; 28 | } -------------------------------------------------------------------------------- /23.1 UsingFind.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int main() 6 | { 7 | using namespace std; 8 | vector numsInVec{ 2017, 0, -1, 42, 10101, 25 }; 9 | 10 | cout << "Enter number to find in collection: "; 11 | int numToFind = 0; 12 | cin >> numToFind; 13 | 14 | auto element = find(numsInVec.cbegin(), // Start of range 15 | numsInVec.cend(), // End of range 16 | numToFind); // Element to find 17 | 18 | // Check if find succeeded 19 | if(element != numsInVec.cend()) 20 | cout << "Value " << *element << " found!" << endl; 21 | else 22 | cout << "No element contains value " << numToFind << endl; 23 | 24 | cout << "Finding the first even number using find_if: " << endl; 25 | 26 | auto evenNum = find_if(numsInVec.cbegin(), // Start of range 27 | numsInVec.cend(), // End of range 28 | [](int element) { return(element % 2) == 0; }); 29 | 30 | if(evenNum != numsInVec.cend()) 31 | { 32 | cout << "Number '" << *evenNum << "' found at position ["; 33 | cout << distance(numsInVec.cbegin(), evenNum) << "]" << endl; 34 | } 35 | 36 | return 0; 37 | } -------------------------------------------------------------------------------- /23.10 SortUniqueBS.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | template 8 | void DisplayContents(const T& container) 9 | { 10 | for_each(container.begin(), container.end(), 11 | [](const auto& element) {cout << element << ' '; }); 12 | } 13 | 14 | int main() 15 | { 16 | vector names{"John", "jack", "sean", "Anna"}; 17 | 18 | // insert a duplicate 19 | names.push_back("jack"); 20 | 21 | cout << "The initial contents of the vector are:\n"; 22 | DisplayContents(names); 23 | 24 | cout << "\nThe sorted vector contains names in the order:\n"; 25 | sort(names.begin(), names.end()); 26 | DisplayContents(names); 27 | 28 | cout << "\nSearching for \"John\" using 'binary_search':\n"; 29 | bool found = binary_search(names.begin(), names.end(), "John"); 30 | 31 | if(found) 32 | cout << "Result: \"John\" was found in the vector!\n"; 33 | else 34 | cout << "Element not found " << endl; 35 | 36 | // Erase adjacent duplicates 37 | auto newEnd = unique(names.begin(), names.end()); 38 | names.erase(newEnd, names.end()); 39 | 40 | cout << "The contents of the vector after using 'unique':\n"; 41 | DisplayContents(names); 42 | 43 | return 0; 44 | } -------------------------------------------------------------------------------- /23.11 PartitionStablePartition.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | auto IsEven = [](const int& num) { return((num % 2) == 0); }; 7 | 8 | template 9 | void DisplayContents(const T& container) 10 | { 11 | for_each(container.begin(), container.end(), 12 | [](const auto& element) {cout << element << ' '; }); 13 | 14 | cout << "| Number of elements: " << container.size() << endl; 15 | } 16 | 17 | int main() 18 | { 19 | vector numsInVec{ 2017, 0, -1, 42, 10101, 25 }; 20 | 21 | cout << "The initial contents: " << endl; 22 | DisplayContents(numsInVec); 23 | 24 | vector vecCopy(numsInVec); 25 | 26 | cout << "The effect of using partition():" << endl; 27 | partition(numsInVec.begin(), numsInVec.end(), IsEven); 28 | DisplayContents(numsInVec); 29 | 30 | cout << "The effect of using stable_partition():" << endl; 31 | stable_partition(vecCopy.begin(), vecCopy.end(), IsEven); 32 | DisplayContents(vecCopy); 33 | 34 | return 0; 35 | } -------------------------------------------------------------------------------- /23.12 LowerBoundUpperBound.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | template 8 | void DisplayContents(const T& container) 9 | { 10 | for_each(container.begin(), container.end(), 11 | [](const auto& element) {cout << element << ' '; }); 12 | } 13 | 14 | int main() 15 | { 16 | list names{ "John", "Brad", "jack", "sean", "Anna" }; 17 | 18 | cout << "Sorted contents of the list are: " << endl; 19 | names.sort(); 20 | DisplayContents(names); 21 | 22 | cout << "\nLowest index where \"Brad\" can be inserted is: "; 23 | auto minPos = lower_bound(names.begin(), names.end(), "Brad"); 24 | cout << distance(names.begin(), minPos) << endl; 25 | 26 | cout << "The highest index where \"Brad\" can be inserted is: "; 27 | auto maxPos = upper_bound(names.begin(), names.end(), "Brad"); 28 | cout << distance(names.begin(), maxPos) << endl; 29 | 30 | cout << "List after inserting Brad in sorted order: " << endl; 31 | names.insert(minPos, "Brad"); 32 | DisplayContents(names); 33 | 34 | return 0; 35 | } -------------------------------------------------------------------------------- /23.14 RangesConstrainedAlgorithms.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | template 8 | void DisplayContents(const T& container) 9 | { 10 | for (const auto& element : container) 11 | cout << element << ' '; 12 | 13 | cout << endl; 14 | } 15 | 16 | int main() 17 | { 18 | vector numsInVec{ 2021, -1, 42, 404949, -981 }; 19 | cout << "Initial contents of vector: "; 20 | DisplayContents(numsInVec); 21 | 22 | cout << "Enter integer to search for: "; 23 | int numToFind = 0; 24 | cin >> numToFind; 25 | 26 | auto element = std::ranges::find(numsInVec, numToFind); 27 | if (element != numsInVec.end()) 28 | cout << "Value " << *element << " found!" << endl; 29 | else 30 | cout << "The number isn't in the range\n"; 31 | 32 | std::ranges::sort(numsInVec); 33 | cout << "Sorting the range now\n"; 34 | DisplayContents(numsInVec); 35 | 36 | std::ranges::fill(numsInVec, 0); 37 | cout << "Reset vector contains: "; 38 | DisplayContents(numsInVec); 39 | 40 | string strHello("Hello C++20 constrained algorithms"); 41 | cout << "Original string: " << strHello << endl; 42 | std::ranges::for_each(strHello, [](auto& c) {c = ::tolower(c); }); 43 | cout << "In lower case: " << strHello << endl; 44 | 45 | return 0; 46 | } -------------------------------------------------------------------------------- /23.2 UsingCount.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | // unary predicate for *_if functions 6 | auto IsEven = [](const auto& number) {return((number % 2) == 0); }; 7 | 8 | int main() 9 | { 10 | using namespace std; 11 | vector numsInVec{ 2017, 0, -1, 42, 10101, 25 }; 12 | 13 | size_t numZeroes = count(numsInVec.cbegin(), numsInVec.cend(), 0); 14 | cout << "Number of instances of '0': " << numZeroes << endl; 15 | 16 | size_t numEvenNums = count_if(numsInVec.cbegin(), 17 | numsInVec.cend(), IsEven); 18 | 19 | cout << "Number of even elements: " << numEvenNums << endl; 20 | cout << "Number of odd elements: "; 21 | cout << numsInVec.size() - numEvenNums << endl; 22 | 23 | return 0; 24 | } -------------------------------------------------------------------------------- /23.4 FillAndFillN.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int main() 6 | { 7 | using namespace std; 8 | 9 | // Initialize a sample vector with 3 elements 10 | vector numsInVec(3); 11 | 12 | // fill all elements in the container with value 9 13 | fill(numsInVec.begin(), numsInVec.end(), 9); 14 | 15 | // Increase the size of the vector to hold 6 elements 16 | numsInVec.resize(6); 17 | 18 | // Fill three elements starting at offset position 3 with value -9 19 | fill_n(numsInVec.begin() + 3, 3, -9); 20 | 21 | cout << "Contents of the vector are: " << endl; 22 | for(size_t index = 0; index < numsInVec.size(); ++ index) 23 | { 24 | cout << "Element [" << index << "] = "; 25 | cout << numsInVec [index] << endl; 26 | } 27 | 28 | return 0; 29 | } -------------------------------------------------------------------------------- /23.5 UsingGenerate.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | int main() 8 | { 9 | using namespace std; 10 | 11 | auto t = time(NULL); 12 | srand(static_cast(time(NULL))); 13 | 14 | vector numsInVec(5); 15 | generate(numsInVec.begin(), numsInVec.end(), // range 16 | rand); // generator function 17 | 18 | cout << "Elements in the vector are: "; 19 | for(size_t index = 0; index < numsInVec.size(); ++ index) 20 | cout << numsInVec [index] << " "; 21 | cout << endl; 22 | 23 | list numsInList(5); 24 | generate_n(numsInList.begin(), 3, rand); 25 | 26 | cout << "Elements in the list are: "; 27 | for(auto element = numsInList.begin(); 28 | element != numsInList.end(); 29 | ++ element) 30 | cout << *element << ' '; 31 | 32 | return 0; 33 | } -------------------------------------------------------------------------------- /23.6 UsingForEach.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | template 8 | struct DisplayElementKeepcount 9 | { 10 | int count; 11 | DisplayElementKeepcount(): count(0) {} 12 | 13 | void operator()(const elementType& element) 14 | { 15 | ++ count; 16 | cout << element << ' '; 17 | } 18 | }; 19 | 20 | int main() 21 | { 22 | vector numsInVec{ 2017, 0, -1, 42, 10101, 25 }; 23 | 24 | cout << "Elements in vector are: " << endl; 25 | DisplayElementKeepcount functor = 26 | for_each(numsInVec.cbegin(), // Start of range 27 | numsInVec.cend(), // End of range 28 | DisplayElementKeepcount());// functor 29 | cout << endl; 30 | 31 | // Use the state stored in the return value of for_each! 32 | cout << "'" << functor.count << "' elements displayed" << endl; 33 | 34 | string str("for_each and strings!"); 35 | cout << "Sample string: " << str << endl; 36 | 37 | cout << "Characters displayed using lambda:" << endl; 38 | int numElements = 0; 39 | for_each(str.cbegin(), 40 | str.cend(), 41 | [&numElements](auto c) { cout << c << ' '; ++numElements; }); 42 | 43 | cout << endl; 44 | cout << "'" << numElements << "' characters displayed" << endl; 45 | 46 | return 0; 47 | } -------------------------------------------------------------------------------- /23.9 ReplaceReplaceIf.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | template 7 | void DisplayContents(const T& container) 8 | { 9 | for_each(container.begin(), container.end(), 10 | [](const auto& element) {cout << element << ' '; }); 11 | 12 | cout << endl; 13 | } 14 | 15 | int main() 16 | { 17 | vector numsInVec{232, 5, -98, -3, 5, 0, 987}; 18 | 19 | cout << "The initial contents of vector:\n"; 20 | DisplayContents(numsInVec); 21 | 22 | replace(numsInVec.begin(), numsInVec.end(), 5, 8); 23 | cout << "After replacing value 5 by 8\n"; 24 | DisplayContents(numsInVec); 25 | 26 | replace_if(numsInVec.begin(), numsInVec.end(), 27 | [](int element) {return((element % 2) == 0); }, -1); 28 | cout << "After replacing even values by -1:\n"; 29 | DisplayContents(numsInVec); 30 | 31 | return 0; 32 | } -------------------------------------------------------------------------------- /23.Ex2 IteratorsCopy.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | int main() 10 | { 11 | list listNames; 12 | listNames.push_back("Jack"); 13 | listNames.push_back("John"); 14 | listNames.push_back("Anna"); 15 | listNames.push_back("Skate"); 16 | 17 | vector vecNames(4); 18 | copy(listNames.begin(), listNames.end(), vecNames.begin()); 19 | 20 | vector ::const_iterator iNames; 21 | for_each(vecNames.begin(), vecNames.end(), 22 | [](const auto& name) {cout << name << ' '; }); 23 | 24 | return 0; 25 | } -------------------------------------------------------------------------------- /24.1 InstantiatingStack.cpp: -------------------------------------------------------------------------------- 1 | // This code demonstrates instantiation, produces no output 2 | #include 3 | #include 4 | 5 | int main() 6 | { 7 | using namespace std; 8 | 9 | // A stack of integers 10 | stack numsInStack; 11 | 12 | // A stack of doubles 13 | stack dblsInStack; 14 | 15 | // A stack of doubles contained in a vector 16 | stack > doublesStackedInVec; 17 | 18 | // initializing one stack to be a copy of another 19 | stack numsInStackCopy(numsInStack); 20 | 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /24.2 StackPushPop.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | using namespace std; 7 | stack numsInStack; 8 | 9 | // push: insert values at top of the stack 10 | cout << "Pushing {25, 10, -1, 5} on stack in that order:\n"; 11 | numsInStack.push(25); 12 | numsInStack.push(10); 13 | numsInStack.push(-1); 14 | numsInStack.push(5); 15 | 16 | cout << "Stack contains " << numsInStack.size() << " elements\n"; 17 | while(numsInStack.size() != 0) 18 | { 19 | cout << "Popping topmost element: " << numsInStack.top() << endl; 20 | numsInStack.pop(); // pop: removes topmost element 21 | } 22 | 23 | if(numsInStack.empty()) // true: due to previous pop()s 24 | cout << "Popping all elements empties stack!\n"; 25 | 26 | return 0; 27 | } -------------------------------------------------------------------------------- /24.2 StackPushPop.cpp~: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | template 7 | void DisplayContents(const T& Input) 8 | { 9 | for_each( Input.cbegin() // auto, cbegin: c++11 10 | , Input.cend() // cend() is new in C++11 11 | , [](const T::value_type& element) { cout << element << ' ';}); 12 | 13 | cout << "| Number of elements: " << Input.size() << endl; 14 | } 15 | 16 | int main() 17 | { 18 | stack stackInts; 19 | 20 | stackInts.push(25); 21 | stackInts.push(10); 22 | stackInts.push(-1); 23 | stackInts.push(5); 24 | 25 | cout << "Elements in stack are: " << endl; 26 | DisplayContents(stackInts._Get_container()); 27 | 28 | // pop = remove the topmost element 29 | cout << endl << "Popping them one after another..." << endl; 30 | 31 | while(stackInts.size() != 0) 32 | { 33 | cout << "The element at the top is: " << stackInts.top(); 34 | cout << endl << "Removing it from the stack!" << endl; 35 | 36 | // Remove the topmost element 37 | stackInts.pop(); 38 | } 39 | 40 | if(stackInts.empty()) 41 | cout << endl << "The stack is now empty!"; 42 | 43 | return 0; 44 | } 45 | -------------------------------------------------------------------------------- /24.3 STLQueue.cpp: -------------------------------------------------------------------------------- 1 | // Demonstrates queue instantiation. Produces no output 2 | #include 3 | #include 4 | 5 | int main() 6 | { 7 | using namespace std; 8 | 9 | // A queue of integers 10 | queue numsInQ; 11 | 12 | // A queue of doubles 13 | queue dblsInQ; 14 | 15 | // A queue of doubles stored internally in a list 16 | queue > dblsInQInList; 17 | 18 | // one queue created as a copy of another 19 | queue copyQ(numsInQ); 20 | 21 | return 0; 22 | } -------------------------------------------------------------------------------- /24.4 QueueOperations.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | using namespace std; 7 | queue numsInQ; 8 | 9 | cout << "Inserting {10, 5, -1, 20} into queue\n"; 10 | numsInQ.push(10); 11 | numsInQ.push(5); // elements are inserted at the end 12 | numsInQ.push(-1); 13 | numsInQ.push(20); 14 | 15 | cout << "Queue contains " << numsInQ.size() << " elements\n"; 16 | cout << "Element at front: " << numsInQ.front() << endl; 17 | cout << "Element at back: " << numsInQ.back() << endl; 18 | 19 | while(numsInQ.size() != 0) 20 | { 21 | cout << "Deleting element: " << numsInQ.front() << endl; 22 | numsInQ.pop(); // removes element at front 23 | } 24 | 25 | if(numsInQ.empty()) 26 | cout << "The queue is now empty!" << endl; 27 | 28 | return 0; 29 | } -------------------------------------------------------------------------------- /24.5 InstantiatingPriorityQueue.cpp: -------------------------------------------------------------------------------- 1 | // Demonstrates instantiation. Produces no output 2 | #include 3 | #include 4 | 5 | int main() 6 | { 7 | using namespace std; 8 | 9 | // Priority queue of int sorted using std::less <>(default) 10 | priority_queue numsInPrioQ; 11 | 12 | // A priority queue of doubles 13 | priority_queue dblsInPrioQ; 14 | 15 | // A priority queue of integers sorted using std::greater <> 16 | priority_queue, greater > numsInDescendingQ; 17 | 18 | // a priority queue created as a copy of another 19 | priority_queue copyQ(numsInPrioQ); 20 | 21 | return 0; 22 | } -------------------------------------------------------------------------------- /24.6 PriorityQueueOperations.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | using namespace std; 7 | 8 | priority_queue numsInPrioQ; 9 | cout << "Inserting {10, 5, -1, 20} into the priority_queue" << endl; 10 | numsInPrioQ.push(10); 11 | numsInPrioQ.push(5); 12 | numsInPrioQ.push(-1); 13 | numsInPrioQ.push(20); 14 | 15 | cout << "Deleting the " << numsInPrioQ.size() << " elements" << endl; 16 | while(!numsInPrioQ.empty()) 17 | { 18 | cout << "Deleting topmost element: " << numsInPrioQ.top() << endl; 19 | numsInPrioQ.pop(); 20 | } 21 | 22 | return 0; 23 | } -------------------------------------------------------------------------------- /24.7 PriorityQueueWithPredicate.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | int main() 5 | { 6 | using namespace std; 7 | 8 | // Define a priority_queue object with greater as predicate 9 | priority_queue , greater > numsInPrioQ; 10 | 11 | cout << "Inserting {10, 5, -1, 20} into the priority queue" << endl; 12 | numsInPrioQ.push(10); 13 | numsInPrioQ.push(5); 14 | numsInPrioQ.push(-1); 15 | numsInPrioQ.push(20); 16 | 17 | cout << "Deleting " << numsInPrioQ.size() << " elements" << endl; 18 | while(!numsInPrioQ.empty()) 19 | { 20 | cout << "Deleting topmost element " << numsInPrioQ.top() << endl; 21 | numsInPrioQ.pop(); 22 | } 23 | 24 | return 0; 25 | } -------------------------------------------------------------------------------- /25.1 InstantiatingBitSet.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int main() 6 | { 7 | using namespace std; 8 | 9 | bitset<4> fourBits; // 4 bits initialized to 0000 10 | cout << "Initial contents of fourBits: " << fourBits << endl; 11 | 12 | bitset<5> fiveBits("10101"); // 5 bits 10101 13 | cout << "Initial contents of fiveBits: " << fiveBits << endl; 14 | 15 | bitset<6> sixBits(0b100001); // binary literal introduced in C++14 16 | cout << "Initial contents of sixBits: " << sixBits << endl; 17 | 18 | bitset<8> eightbits(255); // 8 bits initialized to integer 255 19 | cout << "Initial contents of eightBits: " << eightbits << endl; 20 | 21 | // instantiate one bitset as a copy of another 22 | bitset<8> eightBitsCopy(eightbits); 23 | 24 | return 0; 25 | } -------------------------------------------------------------------------------- /25.2 BitSetOperations.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int main() 6 | { 7 | using namespace std; 8 | bitset<8> inputBits; 9 | cout << "Enter a 8-bit sequence: "; 10 | 11 | cin >> inputBits; // store user input in bitset 12 | 13 | cout << "Num 1s you supplied: " << inputBits.count() << endl; 14 | cout << "Num 0s you supplied: "; 15 | cout << inputBits.size() - inputBits.count() << endl; 16 | 17 | bitset<8> inputFlipped (inputBits); // copy 18 | inputFlipped.flip(); // toggle the bits 19 | 20 | cout << "Flipped version is: " << inputFlipped << endl; 21 | 22 | cout << "Result of AND, OR and XOR between the two:" << endl; 23 | cout << inputBits << " & " << inputFlipped << " = "; 24 | cout << (inputBits & inputFlipped) << endl; // bitwise AND 25 | 26 | cout << inputBits << " | " << inputFlipped << " = "; 27 | cout << (inputBits | inputFlipped) << endl; // bitwise OR 28 | 29 | cout << inputBits << " ^ " << inputFlipped << " = "; 30 | cout << (inputBits ^ inputFlipped) << endl; // bitwise XOR 31 | 32 | return 0; 33 | } -------------------------------------------------------------------------------- /25.3 InstantiatingVectorBool.cpp: -------------------------------------------------------------------------------- 1 | // Demonstrates instantiation, produces no output 2 | #include 3 | 4 | int main() 5 | { 6 | using namespace std; 7 | 8 | // Instantiate an object using the default constructor 9 | vector boolFlags1; 10 | 11 | // Initialize a vector with 10 elements with value true 12 | vector boolFlags2(10, true); 13 | 14 | // Instantiate one object as a copy of another 15 | vector boolFlags2Copy(boolFlags2); 16 | 17 | return 0; 18 | } 19 | -------------------------------------------------------------------------------- /25.4 UsingVectorBool.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | vector boolFlags{ true, true, false }; // hold 3 bool flags 9 | boolFlags [0] = true; 10 | boolFlags [1] = true; 11 | boolFlags [2] = false; 12 | 13 | boolFlags.push_back(true); // insert a fourth bool at the end 14 | 15 | cout << "The contents of the vector are: " << endl; 16 | for (size_t index = 0; index < boolFlags.size(); ++ index) 17 | cout << boolFlags [index] << ' '; 18 | 19 | cout << endl; 20 | boolFlags.flip(); 21 | 22 | cout << "The contents of the vector are: " << endl; 23 | for_each(boolFlags.cbegin(), boolFlags.cend(), 24 | [](const auto& b) {cout << b << ' '; }); 25 | 26 | cout << endl; 27 | 28 | return 0; 29 | } -------------------------------------------------------------------------------- /25.Ex1 UseBitset.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | // Initialize the bitset to 1001 8 | bitset<4> fourBits("1001"); 9 | 10 | cout << "fourBits: " << fourBits << endl; 11 | 12 | // Initialize another bitset to 0010 13 | bitset<4> fourMoreBits("0010"); 14 | 15 | cout << "fourMoreBits: " << fourMoreBits << endl; 16 | 17 | bitset<8> addResult(fourBits.to_ulong() + fourMoreBits.to_ulong()); 18 | cout << "The result of the addition is: " << addResult; 19 | 20 | return 0; 21 | } -------------------------------------------------------------------------------- /26.1 MinimalSmartPtr.cpp: -------------------------------------------------------------------------------- 1 | template 2 | class smart_pointer 3 | { 4 | private: 5 | T* rawPtr; 6 | public: 7 | smart_pointer(T* pData) : rawPtr(pData) {} // constructor 8 | ~smart_pointer() {delete rawPtr;}; // destructor 9 | 10 | // copy constructor 11 | smart_pointer(const smart_pointer& anotherSP); 12 | // copy assignment operator 13 | smart_pointer& operator=(const smart_pointer& anotherSP); 14 | 15 | T& operator*() const // dereferencing operator 16 | { 17 | return *(rawPtr); 18 | } 19 | 20 | T* operator->() const // member selection operator 21 | { 22 | return rawPtr; 23 | } 24 | }; 25 | 26 | // empty stub to enable compilation 27 | int main() 28 | { 29 | return 0; 30 | } -------------------------------------------------------------------------------- /26.2 DeepCopyPtr.cpp: -------------------------------------------------------------------------------- 1 | template 2 | class deepcopy_smart_ptr 3 | { 4 | private: 5 | T* object; 6 | public: 7 | //... other functions 8 | 9 | // copy constructor of the deepcopy pointer 10 | deepcopy_smart_ptr(const deepcopy_smart_ptr& source) 11 | { 12 | // Clone() is virtual: ensures deep copy of Derived class object 13 | object = source->Clone(); 14 | } 15 | 16 | // copy assignment operator 17 | deepcopy_smart_ptr& operator=(const deepcopy_smart_ptr& source) 18 | { 19 | if(object) 20 | delete object; 21 | 22 | object = source->Clone(); 23 | } 24 | }; 25 | 26 | // stub to ensure build 27 | int main() 28 | { 29 | return 0; 30 | } -------------------------------------------------------------------------------- /26.3 DestructiveCopyPtr.cpp: -------------------------------------------------------------------------------- 1 | template 2 | class destructivecopy_ptr 3 | { 4 | private: 5 | T* object; 6 | public: 7 | destructivecopy_ptr(T* input):object(input) {} 8 | ~destructivecopy_ptr() { delete object; } 9 | 10 | // copy constructor 11 | destructivecopy_ptr(destructivecopy_ptr& source) 12 | { 13 | // Take ownership on copy 14 | object = source.object; 15 | 16 | // destroy source 17 | source.object = 0; 18 | } 19 | 20 | // copy assignment operator 21 | destructivecopy_ptr& operator=(destructivecopy_ptr& source) 22 | { 23 | if(object != source.object) 24 | { 25 | delete object; 26 | object = source.object; 27 | source.object = 0; 28 | } 29 | } 30 | }; 31 | 32 | int main() 33 | { 34 | destructivecopy_ptr num(new int); 35 | destructivecopy_ptr copy = num; 36 | 37 | // num is now invalid 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /26.4 UsingUniquePtr.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Fish 6 | { 7 | public: 8 | Fish() {cout << "Fish: Constructed!" << endl;} 9 | ~Fish() {cout << "Fish: Destructed!" << endl;} 10 | 11 | void Swim() const {cout << "Fish swims in water" << endl;} 12 | }; 13 | 14 | void MakeFishSwim(const unique_ptr& inFish) 15 | { 16 | inFish->Swim(); 17 | } 18 | 19 | int main() 20 | { 21 | unique_ptr smartFish(new Fish); 22 | 23 | smartFish->Swim(); 24 | MakeFishSwim(smartFish); // OK, as MakeFishSwim accepts reference 25 | 26 | unique_ptr copySmartFish; 27 | // copySmartFish = smartFish; // error: operator= is disabled 28 | 29 | unique_ptr sameFish(std::move(smartFish)); 30 | // smartFish is empty henceforth 31 | 32 | return 0; 33 | } -------------------------------------------------------------------------------- /26.Ex2 FishUniquePtr.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Fish 6 | { 7 | public: 8 | Fish() {cout << "Fish: Constructed!" << endl;} 9 | ~Fish() {cout << "Fish: Destructed!" << endl;} 10 | 11 | void Swim() const {cout << "Fish swims in water" << endl;} 12 | }; 13 | 14 | class Carp: public Fish 15 | { 16 | }; 17 | 18 | void MakeFishSwim(const unique_ptr& inFish) 19 | { 20 | inFish->Swim(); 21 | } 22 | 23 | int main() 24 | { 25 | unique_ptr myCarp(new Carp); 26 | MakeFishSwim(myCarp); 27 | 28 | return 0; 29 | } -------------------------------------------------------------------------------- /27.1 CoutFormattingNumbers.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | cout << "Enter an integer: "; 8 | int input = 0; 9 | cin >> input; 10 | 11 | cout << "Integer in octal: " << oct << input << endl; 12 | cout << "Integer in hexadecimal: " << hex << input << endl; 13 | 14 | cout << "Integer in hex using base notation: "; 15 | cout< 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | struct Human 8 | { 9 | char name[20] = "John"; 10 | int age = 40; 11 | char DOB[20] = "1981 Sep 1"; 12 | }; 13 | 14 | int main() 15 | { 16 | Human aPerson; 17 | 18 | ofstream fsOut ("MyBinary.bin", ios_base::out | ios_base::binary); 19 | if (fsOut.is_open()) 20 | { 21 | cout << "Writing one Human to a binary file" << endl; 22 | fsOut.write(reinterpret_cast(&aPerson), sizeof(aPerson)); 23 | fsOut.close(); 24 | } 25 | 26 | ifstream fsIn ("MyBinary.bin", ios_base::in | ios_base::binary); 27 | if(fsIn.is_open()) 28 | { 29 | Human readHuman; 30 | fsIn.read((char*)&readHuman, sizeof(readHuman)); 31 | 32 | cout << "Reading information from binary file: " << endl; 33 | cout << "Name = " << readHuman.name << endl; 34 | cout << "Age = " << readHuman.age << endl; 35 | cout << "Date of Birth = " << readHuman.DOB << endl; 36 | } 37 | 38 | return 0; 39 | } -------------------------------------------------------------------------------- /27.11 StringStream.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | cout << "Enter an integer: "; 9 | int input = 0; 10 | cin >> input; 11 | 12 | stringstream converterStream; 13 | converterStream << input; 14 | string inputAsStr; 15 | converterStream >> inputAsStr; 16 | 17 | cout << "Integer Input = " << input << endl; 18 | cout << "String gained from integer = " << inputAsStr << endl; 19 | 20 | stringstream anotherStream; 21 | anotherStream << inputAsStr; 22 | int copy = 0; 23 | anotherStream >> copy; 24 | 25 | cout << "Integer gained from string, copy = " << copy << endl; 26 | 27 | return 0; 28 | } -------------------------------------------------------------------------------- /27.2 CoutNumPrecision.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | const double Pi =(double)22.0 / 7; 8 | cout << "Pi = " << Pi << endl; 9 | 10 | cout << endl << "Setting precision to 7: " << endl; 11 | cout << setprecision(7); 12 | cout << "Pi = " << Pi << endl; 13 | cout << fixed << "Fixed Pi = " << Pi << endl; 14 | cout << scientific << "Scientific Pi = " << Pi << endl; 15 | 16 | cout << endl << "Setting precision to 10: " << endl; 17 | cout << setprecision(10); 18 | cout << "Pi = " << Pi << endl; 19 | cout << fixed << "Fixed Pi = " << Pi << endl; 20 | cout << scientific << "Scientific Pi = " << Pi << endl; 21 | 22 | cout << endl << "Enter a radius: "; 23 | double radius = 0.0; 24 | cin >> radius; 25 | cout << "Area of circle: " << 2*Pi*radius*radius << endl; 26 | 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /27.3 CoutSetWSetFill.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | cout << "Hey - default!" << endl; 8 | 9 | cout << setw(35); 10 | cout << "Hey - right aligned!" << endl; 11 | 12 | cout << setw(35) << setfill('*'); 13 | cout << "Hey - right aligned!" << endl; 14 | 15 | cout << "Hey - back to default!" << endl; 16 | 17 | return 0; 18 | } -------------------------------------------------------------------------------- /27.4 SimpleInputUsingCin.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | cout << "Enter an integer: "; 7 | int inputNum = 0; 8 | cin >> inputNum; 9 | 10 | cout << "Enter the value of Pi: "; 11 | double Pi = 0.0; 12 | cin >> Pi; 13 | 14 | cout << "Enter three characters separated by space: " << endl; 15 | char char1 = '\0', char2 = '\0', char3 = '\0'; 16 | cin >> char1 >> char2 >> char3; 17 | 18 | cout << "The recorded variable values are: " << endl; 19 | cout << "inputNum: " << inputNum << endl; 20 | cout << "Pi: " << Pi << endl; 21 | cout << "The three characters: " << char1 << char2 << char3 << endl; 22 | 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /27.5 ReadingWordLine.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | cout << "Enter a line: " << endl; 8 | char charBuf[10]; 9 | cin.get(charBuf, 10); 10 | cout << "charBuf: " << charBuf << endl; 11 | 12 | return 0; 13 | } -------------------------------------------------------------------------------- /27.6 CinReadingWordLine.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | cout << "Enter your name: "; 8 | string name; 9 | cin >> name; 10 | cout << "Hi " << name << endl; 11 | 12 | return 0; 13 | } -------------------------------------------------------------------------------- /27.7 UsingGetLine.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | cout << "Enter your name: "; 8 | string name; 9 | getline(cin, name); 10 | cout << "Hi " << name << endl; 11 | 12 | return 0; 13 | } -------------------------------------------------------------------------------- /27.8 WritingToFile.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | ofstream myFile; 8 | myFile.open("HelloFile.txt", ios_base::out); 9 | 10 | if(myFile.is_open()) 11 | { 12 | cout << "File open successful" << endl; 13 | 14 | myFile << "My first text file!" << endl; 15 | myFile << "Hello file!"; 16 | 17 | cout << "Finished writing to file, will close now\n"; 18 | myFile.close(); 19 | } 20 | 21 | return 0; 22 | } -------------------------------------------------------------------------------- /27.9 ReadingTextFile.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | ifstream myFile; 9 | myFile.open("HelloFile.txt", ios_base::in); 10 | 11 | if(myFile.is_open()) 12 | { 13 | cout << "File open successful. It contains: \n"; 14 | string fileContents; 15 | 16 | while(myFile.good()) 17 | { 18 | getline(myFile, fileContents); 19 | cout << fileContents << endl; 20 | } 21 | 22 | cout << "Finished reading file, will close now\n"; 23 | myFile.close(); 24 | } 25 | else 26 | cout << "open() failed: check if file is in right folder\n"; 27 | 28 | return 0; 29 | } -------------------------------------------------------------------------------- /28.1 ExceptionSafetyInNew.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | cout << "Enter number of integers you wish to reserve: "; 7 | try 8 | { 9 | int input = 0; 10 | cin >> input; 11 | 12 | // Request memory space and then return it 13 | int* numArray = new int[input]; 14 | delete[] numArray; 15 | } 16 | catch(...) 17 | { 18 | cout << "Exception occurred. Got to end, sorry!" << endl; 19 | } 20 | return 0; 21 | } -------------------------------------------------------------------------------- /28.2 CatchingAType.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include // include this to catch exception bad_alloc 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | cout << "Enter number of integers you wish to reserve: "; 8 | try 9 | { 10 | int input = 0; 11 | cin >> input; 12 | 13 | // Request memory space and then return it 14 | int* numArray = new int[input]; 15 | delete[] numArray; 16 | } 17 | catch(std::bad_alloc& exp) 18 | { 19 | cout << "Exception encountered: " << exp.what() << endl; 20 | cout << "Got to end, sorry!" << endl; 21 | } 22 | catch(...) 23 | { 24 | cout << "Exception encountered. Got to end, sorry!" << endl; 25 | } 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /28.3 ExceptionOnDivideByZero.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | double Divide(double dividend, double divisor) 5 | { 6 | if(divisor == 0) 7 | throw "Dividing by 0 is a crime"; 8 | 9 | return(dividend / divisor); 10 | } 11 | 12 | int main() 13 | { 14 | cout << "Enter dividend: "; 15 | double dividend = 0; 16 | cin >> dividend; 17 | cout << "Enter divisor: "; 18 | double divisor = 0; 19 | cin >> divisor; 20 | 21 | try 22 | { 23 | cout << "Result is: " << Divide(dividend, divisor); 24 | } 25 | catch(const char* exp) 26 | { 27 | cout << "Exception: " << exp << endl; 28 | cout << "Sorry, can't continue!" << endl; 29 | } 30 | 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /28.4 StackUnwindingOnException.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct StructA 5 | { 6 | StructA() {cout << "StructA constructor" << endl; } 7 | ~StructA() {cout << "StructA destructor" << endl; } 8 | }; 9 | 10 | struct StructB 11 | { 12 | StructB() {cout << "StructB constructor" << endl; } 13 | ~StructB() {cout << "StructB destructor" << endl; } 14 | }; 15 | 16 | void FuncB() // throws 17 | { 18 | cout << "In Func B" << endl; 19 | StructA objA; 20 | StructB objB; 21 | cout << "About to throw up!" << endl; 22 | throw "Throwing for the heck of it"; 23 | } 24 | 25 | void FuncA() 26 | { 27 | try 28 | { 29 | cout << "In Func A" << endl; 30 | StructA objA; 31 | StructB objB; 32 | FuncB(); 33 | cout << "FuncA: returning to caller" << endl; 34 | } 35 | catch(const char* exp) 36 | { 37 | cout << "FuncA: Caught exception: " << exp << endl; 38 | cout << "Handled it, will not throw to caller" << endl; 39 | // throw; // uncomment this line to throw to main() 40 | } 41 | } 42 | 43 | int main() 44 | { 45 | cout << "main(): Started execution" << endl; 46 | try 47 | { 48 | FuncA(); 49 | } 50 | catch(const char* exp) 51 | { 52 | cout << "Exception: " << exp << endl; 53 | } 54 | cout << "main(): exiting gracefully" << endl; 55 | return 0; 56 | } -------------------------------------------------------------------------------- /28.5 CustomException.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class CustomException: public std::exception 7 | { 8 | string reason; 9 | public: 10 | // constructor, needs reason 11 | CustomException(const char* why):reason(why) {} 12 | 13 | // redefining virtual function to return 'reason' 14 | virtual const char* what() const throw() 15 | { 16 | return reason.c_str(); 17 | } 18 | }; 19 | 20 | double Divide(double dividend, double divisor) 21 | { 22 | if(divisor == 0) 23 | throw CustomException("CustomException: Division by 0"); 24 | 25 | return(dividend / divisor); 26 | } 27 | 28 | int main() 29 | { 30 | cout << "Enter dividend: "; 31 | double dividend = 0; 32 | cin >> dividend; 33 | cout << "Enter divisor: "; 34 | double divisor = 0; 35 | cin >> divisor; 36 | try 37 | { 38 | cout << "Result is: " << Divide(dividend, divisor); 39 | } 40 | catch(exception& exp)// catch CustomException, bad_alloc, etc 41 | { 42 | cout << exp.what() << endl; 43 | cout << "Sorry, can't continue!" << endl; 44 | } 45 | 46 | return 0; 47 | } -------------------------------------------------------------------------------- /29.1 ConceptFloatingPt.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | template // enforce floating point 6 | double DivideNums(T dividend, T divisor) 7 | { 8 | return (dividend / divisor); 9 | } 10 | 11 | int main() 12 | { 13 | cout << "Pi = " << DivideNums(22.0, 7.0); // OK 14 | // cout << "Pi = " << DivideNums(22, 7); // err: not floating pt 15 | 16 | return 0; 17 | } -------------------------------------------------------------------------------- /29.3 ConceptsWithClasses.cpp: -------------------------------------------------------------------------------- 1 | // C++20 sample. Use appropriate compiler settings 2 | // Demonstrates concepts 3 | 4 | #include 5 | using namespace std; 6 | 7 | template 8 | concept AnyNumericType = floating_point || integral; 9 | 10 | template 11 | class Person 12 | { 13 | public: 14 | T1 age; 15 | T2 yearsEmployed; 16 | 17 | Person(T1 num1, T2 num2) : age(num1), yearsEmployed(num2) {} 18 | }; 19 | 20 | int main() 21 | { 22 | Person p1(21, 3.4); // OK 23 | Person p2(32.6, 3.4f); // OK 24 | 25 | // Person p3("lara", 3.4); // error: "lara" isn't numeric 26 | 27 | return 0; 28 | } -------------------------------------------------------------------------------- /29.4 ConceptDerivedFrom.cpp: -------------------------------------------------------------------------------- 1 | // C++20 sample. Use appropriate compiler settings 2 | // Demonstrates concept derived_from 3 | 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | class Base {}; 9 | class PublicDerived : public Base {}; 10 | class PrivateDerived : private Base {}; 11 | class Unrelated {}; 12 | 13 | template T> 14 | void ProcessBaseTypesOnly(T& input) 15 | { 16 | cout << "Processing an instance of Base" << endl; 17 | } 18 | 19 | int main() 20 | { 21 | static_assert(derived_from /* == true */); 22 | static_assert(derived_from == false); 23 | static_assert(derived_from == false); 24 | 25 | PublicDerived d1; 26 | PrivateDerived d2; 27 | Unrelated u; 28 | ProcessBaseTypesOnly(d1); // OK, d1 is also type Base 29 | // ProcessBaseTypesOnly(d2); // Error: d2 isn't a Base 30 | // ProcessBaseTypesOnly(u); // Error: u is unrelated to Base 31 | 32 | return 0; 33 | } -------------------------------------------------------------------------------- /29.5 RangesIntro.cpp: -------------------------------------------------------------------------------- 1 | // C++20 sample. Use appropriate compiler settings 2 | // Demonstrates concepts supplied by std::ranges 3 | // Produces no output 4 | 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | using namespace std; 13 | 14 | int main() 15 | { 16 | static_assert(ranges::range); 17 | static_assert(ranges::range>); 18 | static_assert(ranges::range>); 19 | static_assert(ranges::range>); 20 | static_assert(ranges::range>); 21 | 22 | static_assert(ranges::forward_range>); 23 | static_assert(ranges::random_access_range>); 24 | static_assert(ranges::bidirectional_range>); 25 | 26 | // static_assert(ranges::range>); // error: stack isn't a range 27 | // static_assert(ranges::bidirectional_range>); // error: forward_list isn't bidirectional 28 | // static_assert(ranges::random_access_range>); // error: set doesnt support random access iteration 29 | 30 | return 0; 31 | } -------------------------------------------------------------------------------- /29.6 ViewsReverse.cpp: -------------------------------------------------------------------------------- 1 | // C++20 sample. Use appropriate compiler settings 2 | // Demonstrates views and adapter reverse supplied by std::ranges 3 | 4 | #include 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | int main() 10 | { 11 | vector nums{ 1, 5, 202, -99, 42, 50 }; 12 | 13 | // create a view using adaptor reverse 14 | auto viewReverse = nums | std::views::reverse; 15 | 16 | cout << "View of collection in reverse: "; 17 | // range-based for: because, a view is also a range 18 | for (int num : viewReverse) 19 | cout << num << ' '; 20 | 21 | cout << endl << "Original collection (unchanged): "; 22 | for (int num : nums) 23 | cout << num << ' '; 24 | 25 | return 0; 26 | } -------------------------------------------------------------------------------- /29.8 CombiningAdaptors.cpp: -------------------------------------------------------------------------------- 1 | // C++20 sample. Use appropriate compiler settings 2 | // Demonstrates views and adaptors in std::ranges 3 | 4 | #include 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | // concept ranges::view limits parameter type to view 10 | template 11 | void DisplayView(T& view) 12 | { 13 | for (auto element : view) 14 | cout << element << ' '; 15 | 16 | cout << endl; 17 | } 18 | 19 | int main() 20 | { 21 | vector nums{ 1, 5, 202, -99, 42, 50 }; 22 | auto viewAllElements = nums | std::views::all; 23 | cout << "View of all elements in the collection: "; 24 | DisplayView(viewAllElements); 25 | 26 | auto lambdaIsEven = [](auto num) {return ((num % 2) == 0); }; 27 | auto viewEvenInRev = nums | views::reverse | views::filter(lambdaIsEven); 28 | cout << "View even numbers in reverse: "; 29 | DisplayView(viewEvenInRev); 30 | 31 | auto viewEvenInReverseTopTwo = nums | views::reverse 32 | | views::filter(lambdaIsEven) | views::take(2); 33 | cout << "View first two even numbers in reverse: "; 34 | DisplayView(viewEvenInReverseTopTwo); 35 | 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /29.Ex3 ViewReverseTransform.cpp: -------------------------------------------------------------------------------- 1 | // C++20 sample. Use appropriate compiler settings 2 | // Demonstrates views and adaptors in std::ranges 3 | 4 | #include 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | // concept ranges::view limits parameter type to view 10 | template 11 | void DisplayView(T& view) 12 | { 13 | for (auto element : view) 14 | cout << element << ' '; 15 | 16 | cout << endl; 17 | } 18 | 19 | int main() 20 | { 21 | vector nums{ 1, 5, 202, -99, 42, 50 }; 22 | auto viewAllElements = nums | std::views::all; 23 | cout << "View of all elements in the collection: "; 24 | DisplayView(viewAllElements); 25 | 26 | auto viewSquare3Rev = nums | views::reverse | views::take(3) 27 | | views::transform([](auto num) {return num * num; }); 28 | cout << "View square of numbers, ignoring first three: "; 29 | DisplayView(viewSquare3Rev); 30 | 31 | return 0; 32 | } -------------------------------------------------------------------------------- /3.1 VariablesDemo_MultiplyTwoNumbers.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main () 5 | { 6 | cout << "This program multiplies two numbers" << endl; 7 | 8 | cout << "Enter the first number: "; 9 | int firstNumber = 0; 10 | cin >> firstNumber; 11 | 12 | cout << "Enter the second number: "; 13 | int secondNumber = 0; 14 | cin >> secondNumber; 15 | 16 | // Multiply two numbers, store result in a variable 17 | int multiplicationResult = firstNumber * secondNumber; 18 | 19 | // Display result 20 | cout << firstNumber << " x " << secondNumber; 21 | cout << " = " << multiplicationResult << endl; 22 | 23 | return 0; 24 | } -------------------------------------------------------------------------------- /3.2 VariablesScopeDemo.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void MultiplyNumbers () 5 | { 6 | cout << "Enter the first number: "; 7 | int firstNumber = 0; 8 | cin >> firstNumber; 9 | 10 | cout << "Enter the second number: "; 11 | int secondNumber = 0; 12 | cin >> secondNumber; 13 | 14 | // Multiply numbers, store multiplicationResult in a variable 15 | int multiplicationResult = firstNumber * secondNumber; 16 | 17 | // Display multiplicationResult 18 | cout << firstNumber << " x " << secondNumber << " = "; 19 | cout << multiplicationResult << endl; 20 | } 21 | int main () 22 | { 23 | cout << "This program multiplies two numbers" << endl; 24 | 25 | // Call the function that does all the work 26 | MultiplyNumbers(); 27 | 28 | // cout << firstNumber << " x " << secondNumber; 29 | // cout << " = " << multiplicationResult << endl; 30 | 31 | return 0; 32 | } -------------------------------------------------------------------------------- /3.3 GlobalVariablesDemo.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Declare three global integers 5 | int firstNumber = 0; 6 | int secondNumber = 0; 7 | int multiplicationResult = 0; 8 | 9 | void MultiplyNumbers () 10 | { 11 | cout << "Enter the first number: "; 12 | cin >> firstNumber; 13 | 14 | cout << "Enter the second number: "; 15 | cin >> secondNumber; 16 | 17 | // Multiply two numbers, store result in a variable 18 | multiplicationResult = firstNumber * secondNumber; 19 | 20 | // Display multiplicationResult 21 | cout << "Displaying from MultiplyNumbers(): "; 22 | cout << firstNumber << " x " << secondNumber; 23 | cout << " = " << multiplicationResult << endl; 24 | } 25 | int main () 26 | { 27 | cout << "This program multiplies two numbers" << endl; 28 | 29 | // Call the function that does all the work 30 | MultiplyNumbers(); 31 | 32 | cout << "Displaying from main(): "; 33 | 34 | // This line will now compile and work! 35 | cout << firstNumber << " x " << secondNumber; 36 | cout << " = " << multiplicationResult << endl; 37 | 38 | return 0; 39 | } -------------------------------------------------------------------------------- /3.4 Operators_Signed_Unsigned_Overflow.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | unsigned short uShortValue = 65535; 7 | cout << "unsigned short 65535 + 1 = "; 8 | cout << ++uShortValue << endl; 9 | 10 | short signedShort = 32767; 11 | cout << "signed short 32767 + 1 = "; 12 | cout << ++signedShort << endl; 13 | 14 | return 0; 15 | } -------------------------------------------------------------------------------- /3.5 Using_sizeof.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | using namespace std; 6 | cout << "Computing the size of inbuilt variable types" << endl; 7 | 8 | cout << "sizeof bool: " << sizeof(bool) << endl; 9 | cout << "sizeof char: " << sizeof(char) << endl; 10 | cout << "sizeof unsigned short int: " << sizeof(unsigned short) << endl; 11 | cout << "sizeof short int: " << sizeof(short) << endl; 12 | cout << "sizeof unsigned long int: " << sizeof(unsigned long) << endl; 13 | cout << "sizeof long: " << sizeof(long) << endl; 14 | cout << "sizeof int: " << sizeof(int) << endl; 15 | cout << "sizeof uns. long long: "<< sizeof(unsigned long long)<< endl; 16 | cout << "sizeof long long: " << sizeof(long long) << endl; 17 | cout << "sizeof unsigned int: " << sizeof(unsigned int) << endl; 18 | cout << "sizeof float: " << sizeof(float) << endl; 19 | cout << "sizeof double: " << sizeof(double) << endl; 20 | 21 | cout << "The output changes with compiler, hardware and OS" << endl; 22 | 23 | return 0; 24 | } -------------------------------------------------------------------------------- /3.7 Demo_Constants.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | using namespace std; 6 | 7 | const double pi = 22.0 / 7; 8 | cout << "The value of constant pi is: " << pi << endl; 9 | 10 | // Uncomment next line to fail compilation 11 | // pi = 345; // error, assignment to a constant 12 | 13 | return 0; 14 | } -------------------------------------------------------------------------------- /3.8 using constexpr.cpp: -------------------------------------------------------------------------------- 1 | // 3.8 using constexpr.cpp : Defines the entry point for the console application. 2 | // 3 | 4 | #include 5 | consteval double GetPi() { return 22.0 / 7; } 6 | constexpr double XPi(int x) { return x * GetPi(); } 7 | 8 | int main() 9 | { 10 | using namespace std; 11 | constexpr double pi = GetPi(); // evaluated by compiler 12 | 13 | cout << "constexpr pi evaluated by compiler to " << pi << endl; 14 | cout << "constexpr XPi(2) evaluated by compiler to " << XPi(2) << endl; 15 | 16 | int multiple = 5; 17 | cout << "(non-const) integer multiple = " << multiple << endl; 18 | cout << "constexpr is ignored when XPi(multiple) is invoked, "; 19 | cout << "returns " << XPi(multiple) << endl; 20 | 21 | return 0; 22 | } -------------------------------------------------------------------------------- /3.9 Using_enum_Constants.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | enum CardinalDirections 5 | { 6 | North = 25, 7 | South, 8 | East, 9 | West 10 | }; 11 | 12 | int main() 13 | { 14 | cout << "Displaying directions and their symbolic values" << endl; 15 | cout << "North: " << North << endl; 16 | cout << "South: " << South << endl; 17 | cout << "East: " << East << endl; 18 | cout << "West: " << West << endl; 19 | 20 | CardinalDirections windDirection = South; 21 | cout << "Variable windDirection = " << windDirection << endl; 22 | 23 | return 0; 24 | } -------------------------------------------------------------------------------- /3.Ex3 Calculate_Area_Circumference.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | const double Pi = 3.1416; 7 | 8 | cout << "Enter circle's radius: "; 9 | double Radius = 0; 10 | cin >> Radius; 11 | 12 | cout << "Area = " << Pi * Radius * Radius << endl; 13 | cout << "Circumference = " << 2 * Pi * Radius << endl; 14 | 15 | return 0; 16 | } -------------------------------------------------------------------------------- /30.1 jthread.cpp: -------------------------------------------------------------------------------- 1 | // C++20 code demonstrates jthread 2 | // Remember to enable compiler settings for C++20 3 | // (some versions of g++ may require you to add -pthread) 4 | 5 | #include 6 | #include 7 | #include 8 | using namespace std; 9 | 10 | void ThreadFunction(std::stop_token stopSoon) 11 | { 12 | while (true) 13 | { 14 | cout << "Worker thread: Hello!\n"; 15 | std::this_thread::sleep_for(1s); 16 | 17 | if (stopSoon.stop_requested()) 18 | { 19 | cout << "Worker thread: asked to end, bye\n"; 20 | break; 21 | } 22 | } 23 | } 24 | 25 | int main() 26 | { 27 | cout << "Main thread: Starting a worker thread\n"; 28 | 29 | // Construct a thread object (it starts execution too) 30 | jthread thSayHello(ThreadFunction); 31 | 32 | // pause the main thread for 5 seconds 33 | this_thread::sleep_for(5s); 34 | 35 | cout << "Main thread: Sending a stop request to worker\n"; 36 | // send a stop "request" to child thread (not a kill) 37 | thSayHello.request_stop(); 38 | 39 | if (thSayHello.joinable()) 40 | { 41 | cout << "Main thread: Waiting on worker to end\n"; 42 | thSayHello.join(); // waiting on thread to end 43 | cout << "Main thread: wait has ended. Exiting now\n"; 44 | } 45 | 46 | return 0; 47 | } -------------------------------------------------------------------------------- /31.1 ModulesHelloWorld.cpp: -------------------------------------------------------------------------------- 1 | // C++20 modules: enable the right compiler settings 2 | // This sample is MSVC specific because the modularzation of 3 | // standard headers (in std.core, for ex.) is not standardized 4 | 5 | import std.core; 6 | 7 | int main() 8 | { 9 | std::cout << "Hello World!" << std::endl; 10 | return 0; 11 | } 12 | -------------------------------------------------------------------------------- /31.2 ImportModuleMain.cpp: -------------------------------------------------------------------------------- 1 | // Sample of C++20 Modules. Use the right compiler settings 2 | // main() uses SimpleOperations, to be found in 3 | // 31.2 SimpleOperations.ixx: module interface unit 4 | // 31.2 SimpleOperations.cpp: module implementation unit 5 | // Add these to your MSVC project 6 | 7 | import std.core; 8 | import SimpleOperations; 9 | 10 | int main() 11 | { 12 | int sum = AddIntegers(500, 50); 13 | int difference = SubtractIntegers(500, 50); 14 | 15 | return 0; 16 | } -------------------------------------------------------------------------------- /31.2 SimpleOperations.cpp: -------------------------------------------------------------------------------- 1 | // 31.2 SimpleOperations.cpp: module implementation unit 2 | 3 | module SimpleOperations; 4 | 5 | int AddIntegers(int a, int b) 6 | { 7 | return (a + b); 8 | } 9 | 10 | int SubtractIntegers(int a, int b) 11 | { 12 | return (a - b); 13 | } 14 | 15 | void FuncIsNotVisibleOutsideModule(){} 16 | -------------------------------------------------------------------------------- /31.2 SimpleOperations.ixx: -------------------------------------------------------------------------------- 1 | // 31.2 SimpleOperations.ixx: module interface unit 2 | 3 | export module SimpleOperations; 4 | 5 | export int AddIntegers(int a, int b); 6 | export int SubtractIntegers(int a, int b); 7 | export class PairNums 8 | { 9 | public: 10 | int lhs, rhs; 11 | 12 | PairNums(int a, int b) :lhs(a), rhs(b) {} 13 | }; 14 | 15 | void FuncNotVisibleOutsideModule(); 16 | 17 | namespace NamespaceInModule 18 | { 19 | export int t1; 20 | } -------------------------------------------------------------------------------- /4.1 AccessingArrayElements.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main () 5 | { 6 | int myNumbers [5] = {34, 56, -21, 5002, 365}; 7 | 8 | cout << "First element at index 0: " << myNumbers [0] << endl; 9 | cout << "Second element at index 1: " << myNumbers [1] << endl; 10 | cout << "Third element at index 2: " << myNumbers [2] << endl; 11 | cout << "Fourth element at index 3: " << myNumbers [3] << endl; 12 | cout << "Fifth element at index 4: " << myNumbers [4] << endl; 13 | 14 | return 0; 15 | } -------------------------------------------------------------------------------- /4.2 WritingToArrayElements.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | constexpr int Square(int number) { return number*number; } 4 | 5 | int main() 6 | { 7 | const int ARRAY_LENGTH = 5; 8 | 9 | // Array of 5 integers, initialized to five values 10 | int myNumbers [ARRAY_LENGTH] = {5, 10, 0, -101, 20}; 11 | 12 | // Using a constexpr to create an array of 5*5=25 integers 13 | int moreNumbers[Square(ARRAY_LENGTH)]; 14 | 15 | cout << "Enter index of the element to be changed: "; 16 | int elementIndex = 0; 17 | cin >> elementIndex; 18 | 19 | cout << "Enter new value: "; 20 | int newValue = 0; 21 | cin >> newValue; 22 | 23 | myNumbers[elementIndex] = newValue; 24 | moreNumbers[elementIndex] = newValue; 25 | 26 | cout << "Element " << elementIndex << " in array myNumbers is: "; 27 | cout << myNumbers[elementIndex] << endl; 28 | 29 | cout << "Element " << elementIndex << " in array moreNumbers is: "; 30 | cout << moreNumbers[elementIndex] << endl; 31 | 32 | return 0; 33 | } -------------------------------------------------------------------------------- /4.3 Declaring_Initializing_MD_Arrays.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int threeRowsThreeColumns [3][3] = \ 7 | {{-501, 205, 2011}, {989, 101, 206}, {303, 456, 596}}; 8 | 9 | cout << "Row 0: " << threeRowsThreeColumns [0][0] << " " 10 | << threeRowsThreeColumns [0][1] << " " 11 | << threeRowsThreeColumns [0][2] << endl; 12 | 13 | 14 | cout << "Row 1: " << threeRowsThreeColumns [1][0] << " " 15 | << threeRowsThreeColumns [1][1] << " " 16 | << threeRowsThreeColumns [1][2] << endl; 17 | 18 | cout << "Row 2: " << threeRowsThreeColumns [2][0] << " " 19 | << threeRowsThreeColumns [2][1] << " " 20 | << threeRowsThreeColumns [2][2] << endl; 21 | 22 | return 0; 23 | } -------------------------------------------------------------------------------- /4.4 Dynamic_Array_std_vector.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | vector dynArray (3); // note angle brackets (size) 9 | 10 | dynArray[0] = 365; 11 | dynArray[1] = -421; 12 | dynArray[2]= 789; 13 | 14 | cout << "Number of integers in array: " << dynArray.size() << endl; 15 | 16 | cout << "Enter another element to insert" << endl; 17 | int newValue = 0; 18 | cin >> newValue; 19 | dynArray.push_back(newValue); 20 | 21 | cout << "Number of integers in array: " << dynArray.size() << endl; 22 | cout << "Last element in array: "; 23 | cout << dynArray[dynArray.size() - 1] << endl; 24 | 25 | return 0; 26 | } -------------------------------------------------------------------------------- /4.5 C-Style_HelloWorld.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | char sayHello[] = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '\0'}; 7 | cout << sayHello << endl; 8 | cout << "Size of array: " << sizeof(sayHello) << endl; 9 | 10 | cout << "Replacing space with null" << endl; 11 | sayHello[5] = '\0'; 12 | cout << sayHello << endl; 13 | cout << "Size of array: " << sizeof(sayHello) << endl; 14 | 15 | cout << sayHello + 6 << endl; // "World" 16 | 17 | return 0; 18 | } -------------------------------------------------------------------------------- /4.6 UserInput_C_Style_String.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | int main() 5 | { 6 | cout << "Enter a word NOT longer than 20 characters:" << endl; 7 | 8 | char userInput [21]; 9 | cin >> userInput; 10 | 11 | cout << "Length of your input was: " << strlen (userInput) << endl; 12 | 13 | return 0; 14 | } -------------------------------------------------------------------------------- /4.7 CPPStrings_std_string.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | string greetStrings ("Hello std::string!"); 9 | cout << greetStrings << endl; 10 | 11 | cout << "Enter a line of text: " << endl; 12 | string firstLine; 13 | getline(cin, firstLine); 14 | 15 | cout << "Enter another: " << endl; 16 | string secondLine; 17 | getline(cin, secondLine); 18 | 19 | cout << "Result of concatenation: " << endl; 20 | string concatString = firstLine + " " + secondLine; 21 | cout << concatString << endl; 22 | 23 | cout << "Copy of concatenated string: " << endl; 24 | string aCopy; 25 | aCopy = concatString; 26 | cout << aCopy << endl; 27 | 28 | cout << "Length of concat string: " << concatString.length() << endl; 29 | 30 | return 0; 31 | } -------------------------------------------------------------------------------- /4.Ex1.cpp: -------------------------------------------------------------------------------- 1 | int main() 2 | { 3 | enum SQUARE 4 | { 5 | NOTHING = 0, 6 | PAWN, 7 | ROOK, 8 | KNIGHT, 9 | BISHOP, 10 | KING, 11 | QUEEN 12 | }; 13 | 14 | SQUARE ChessBoard[8][8]; // 8 rows x 8 columns 15 | 16 | // Initialize the squares containing rooks 17 | ChessBoard[0][0] = ChessBoard[0][7] = ROOK; 18 | ChessBoard[7][0] = ChessBoard[7][7] = ROOK; 19 | 20 | return 0; 21 | } -------------------------------------------------------------------------------- /5.1 Check_ArithmeticOperators.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | cout << "Enter two integers:" << endl; 7 | int num1 = 0, num2 = 0; 8 | cin >> num1; 9 | cin >> num2; 10 | 11 | cout << num1 << " + " << num2 << " = " << num1 + num2 << endl; 12 | cout << num1 << " - " << num2 << " = " << num1 - num2 << endl; 13 | cout << num1 << " * " << num2 << " = " << num1 * num2 << endl; 14 | cout << num1 << " / " << num2 << " = " << num1 / num2 << endl; 15 | cout << num1 << " % " << num2 << " = " << num1 % num2 << endl; 16 | 17 | return 0; 18 | } -------------------------------------------------------------------------------- /5.10 Operators_CompoundOperators.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | cout << "Enter a number: "; 7 | int value = 0; 8 | cin >> value; 9 | 10 | value += 8; 11 | cout << "After += 8, value = " << value << endl; 12 | value -= 2; 13 | cout << "After -= 2, value = " << value << endl; 14 | value /= 4; 15 | cout << "After /= 4, value = " << value << endl; 16 | value *= 4; 17 | cout << "After *= 4, value = " << value << endl; 18 | value %= 1000; 19 | cout << "After %= 1000, value = " << value << endl; 20 | 21 | // Note: henceforth assignment happens within cout 22 | cout << "After <<= 1, value = " << (value <<= 1) << endl; 23 | cout << "After >>= 2, value = " << (value >>= 2) << endl; 24 | 25 | cout << "After |= 0x55, value = " << (value |= 0x55) << endl; 26 | cout << "After ^= 0x55, value = " << (value ^= 0x55) << endl; 27 | cout << "After &= 0x0F, value = " << (value &= 0x0F) << endl; 28 | 29 | return 0; 30 | } -------------------------------------------------------------------------------- /5.11 Operator_sizeof.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | cout << "Use sizeof to determine memory used by arrays" << endl; 7 | int myNumbers [100]; 8 | 9 | cout << "Bytes used by an int: " << sizeof(int) << endl; 10 | cout << "Bytes used by myNumbers: " << sizeof(myNumbers) << endl; 11 | cout << "Bytes used by an element: " << sizeof(myNumbers[0]) << endl; 12 | 13 | return 0; 14 | } -------------------------------------------------------------------------------- /5.2 Operators_PostFix_Prefix.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int startValue = 101; 7 | cout << "Start value of integer being operated: " << startValue << endl; 8 | 9 | int postfixIncrement = startValue++; 10 | cout << "Result of Postfix Increment = " << postfixIncrement << endl; 11 | cout << "After Postfix Increment, startValue = " << startValue << endl; 12 | 13 | startValue = 101; // Reset 14 | int prefixIncrement = ++startValue; 15 | cout << "Result of Prefix Increment = " << prefixIncrement << endl; 16 | cout << "After Prefix Increment, startValue = " << startValue << endl; 17 | 18 | startValue = 101; 19 | int postfixDecrement = startValue--; 20 | cout << "Result of Postfix Decrement = " << postfixDecrement << endl; 21 | cout << "After Postfix Decrement, startValue = " << startValue << endl; 22 | 23 | startValue = 101; 24 | int prefixDecrement = --startValue; 25 | cout << "Result of Prefix Decrement = " << prefixDecrement << endl; 26 | cout << "After Prefix Decrement, startValue = " << startValue << endl; 27 | 28 | return 0; 29 | } -------------------------------------------------------------------------------- /5.3 Operators_Relational_Equality.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | cout << "Enter two integers:" << endl; 7 | int num1 = 0, num2 = 0; 8 | cin >> num1; 9 | cin >> num2; 10 | 11 | bool isEqual = (num1 == num2); 12 | cout << "equality test: " << isEqual << endl; 13 | 14 | bool isUnequal = (num1 != num2); 15 | cout << "inequality test: " << isUnequal << endl; 16 | 17 | bool isGT = (num1 > num2); // greater than 18 | cout << "" << num1 << " > " << num2 << " test: " << isGT << endl; 19 | 20 | bool isLT = (num1 < num2); // lesser than 21 | cout << "" << num1 << " < " << num2 << " test: " << isLT << endl; 22 | 23 | bool isGTE = (num1 >= num2); // greater than or equal to 24 | cout << "" << num1 << " >= " << num2 << " test: " << isGTE << endl; 25 | 26 | bool isLTE = (num1 <= num2); // lesser than or equal to 27 | cout << "" << num1 << " <= " << num2 << " test: " << isLTE << endl; 28 | 29 | return 0; 30 | } -------------------------------------------------------------------------------- /5.4 ThreeWayComparisonOp.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | int num1, num2; 8 | cout << "Enter two integers" << endl; 9 | cin >> num1; 10 | cin >> num2; 11 | 12 | auto resultofComparison = (num1 <=> num2); // new in C++20! 13 | 14 | if (resultofComparison < 0) 15 | cout << "num1 is less than num2" << endl; 16 | else if (resultofComparison > 0) 17 | cout << "num1 is greater than num2" << endl; 18 | else // comparison evaluates to zero 19 | cout << "They're equal" << endl; 20 | 21 | return 0; 22 | } -------------------------------------------------------------------------------- /5.5 Operators_Logical_AND_OR.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | cout << "Enter true(1) or false(0) for two operands:" << endl; 7 | bool op1 = false, op2 = false; 8 | cin >> op1; 9 | cin >> op2; 10 | 11 | cout << op1 << " AND " << op2 << " = " << (op1 && op2) << endl; 12 | cout << op1 << " OR " << op2 << " = " << (op1 || op2) << endl; 13 | 14 | return 0; 15 | } -------------------------------------------------------------------------------- /5.6 Operators_Logical_And_Or_If.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | cout << "Use boolean values(0 / 1) to answer" << endl; 7 | cout << "Is it raining? "; 8 | bool isRaining = false; 9 | cin >> isRaining; 10 | 11 | cout << "Do you have buses on the streets? "; 12 | bool busesPly = false; 13 | cin >> busesPly; 14 | 15 | // Conditional statement uses logical AND and NOT 16 | if (isRaining && !busesPly) 17 | cout << "You cannot go to work" << endl; 18 | else 19 | cout << "You can go to work" << endl; 20 | 21 | if (isRaining && busesPly) 22 | cout << "Take an umbrella" << endl; 23 | 24 | if ((!isRaining) && busesPly) 25 | cout << "Enjoy the sun and have a nice day" << endl; 26 | 27 | return 0; 28 | } -------------------------------------------------------------------------------- /5.7 Operators_Logical_OR.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | cout << "Answer questions with 0 or 1" << endl; 7 | cout << "Is there a discount on your favorite car? "; 8 | bool onDiscount = false; 9 | cin >> onDiscount; 10 | 11 | cout << "Did you get a fantastic bonus? "; 12 | bool fantasticBonus = false; 13 | cin >> fantasticBonus; 14 | 15 | if (onDiscount || fantasticBonus) 16 | cout << "Congratulations, you can buy that car!" << endl; 17 | else 18 | cout << "Sorry, waiting a while is a good idea" << endl; 19 | 20 | if (!onDiscount) 21 | cout << "Car not on discount" << endl; 22 | 23 | return 0; 24 | } -------------------------------------------------------------------------------- /5.8 Operators_Bitwise.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | cout << "Enter a number (0 - 255): "; 8 | unsigned short inputNum = 0; 9 | cin >> inputNum; 10 | 11 | bitset<8> inputBits (inputNum); 12 | cout << inputNum << " in binary is " << inputBits << endl; 13 | 14 | bitset<8> bitwiseNOT = (~inputNum); 15 | cout << "Bitwise NOT ~" << endl; 16 | cout << "~" << inputBits << " = " << bitwiseNOT << endl; 17 | 18 | cout << "Bitwise AND, & with 00001111" << endl; 19 | bitset<8> bitwiseAND = (0x0F & inputNum);// 0x0F is hex for 0001111 20 | cout << "0001111 & " << inputBits << " = " << bitwiseAND << endl; 21 | 22 | cout << "Bitwise OR, | with 00001111" << endl; 23 | bitset<8> bitwiseOR = (0x0F | inputNum); 24 | cout << "00001111 | " << inputBits << " = " << bitwiseOR << endl; 25 | 26 | cout << "Bitwise XOR, ^ with 00001111" << endl; 27 | bitset<8> bitwiseXOR = (0x0F ^ inputNum); 28 | cout << "00001111 ^ " << inputBits << " = " << bitwiseXOR << endl; 29 | 30 | return 0; 31 | } -------------------------------------------------------------------------------- /5.9 Operators_BitwiseShift.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | cout << "Enter a number: "; 7 | int inputNum = 0; 8 | cin >> inputNum; 9 | 10 | int halfNum = inputNum >> 1; 11 | int quarterNum = inputNum >> 2; 12 | int doubleNum = inputNum << 1; 13 | int quadrupleNum = inputNum << 2; 14 | 15 | cout << "Quarter: " << quarterNum << endl; 16 | cout << "Half: " << halfNum << endl; 17 | cout << "Double: " << doubleNum << endl; 18 | cout << "Quadruple: " << quadrupleNum << endl; 19 | 20 | return 0; 21 | } -------------------------------------------------------------------------------- /5.Ex3.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | cout << "Enter a boolean value true(1) or false(0): "; 7 | bool Value1 = false; 8 | cin >> Value1; 9 | 10 | cout << "Enter another boolean value true(1) or false(0): "; 11 | bool Value2 = false; 12 | cin >> Value2; 13 | 14 | cout << "Result of bitwise operators on these operands: " << endl; 15 | cout << "Bitwise AND: " << (Value1 & Value2) << endl; 16 | cout << "Bitwise OR: " << (Value1 | Value2) << endl; 17 | cout << "Bitwise XOR: " << (Value1 ^ Value2) << endl; 18 | 19 | return 0; 20 | } -------------------------------------------------------------------------------- /5.Quiz5.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | cout << "Enter an integer: "; 7 | int number = 0; 8 | cin >> number; 9 | 10 | int result = ((number << 1) + 5) << 1; // unambiguous even to reader 11 | cout << "((Number * 2) + 5) * 2= " << result << endl; 12 | return 0; 13 | } -------------------------------------------------------------------------------- /6.1 Multiply_or_Add_if_else.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | cout << "Enter two integers: " << endl; 7 | int num1 = 0, num2 = 0; 8 | cin >> num1; 9 | cin >> num2; 10 | 11 | cout << "Enter \'m\' to multiply, anything else to add: "; 12 | char userSelection = '\0'; 13 | cin >> userSelection; 14 | 15 | int result = 0; 16 | if (userSelection == 'm') 17 | result = num1 * num2; 18 | else 19 | result = num1 + num2; 20 | 21 | cout << "result is: " << result << endl; 22 | 23 | return 0; 24 | } -------------------------------------------------------------------------------- /6.10 EnterValuesInAnArray_DisplayArray_for_loop.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | const int ARRAY_LENGTH = 5; 7 | int myNums[ARRAY_LENGTH] = {0}; 8 | 9 | cout << "Populate array of " << ARRAY_LENGTH << " integers" << endl; 10 | 11 | for (int counter = 0; counter < ARRAY_LENGTH; ++counter) 12 | { 13 | cout << "Enter an integer for element " << counter << ": "; 14 | cin >> myNums[counter]; 15 | } 16 | 17 | cout << "Displaying contents of the array: " << endl; 18 | 19 | for (int counter = 0; counter < ARRAY_LENGTH; ++counter) 20 | cout << "Element " << counter << " = " << myNums[counter] << endl; 21 | 22 | return 0; 23 | } -------------------------------------------------------------------------------- /6.11 MultiplyAdd_for_loop.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | for(char userSelection = 'm'; (userSelection != 'x'); ) 7 | { 8 | cout << "Enter the two integers: " << endl; 9 | int num1 = 0, num2 = 0; 10 | cin >> num1; 11 | cin >> num2; 12 | 13 | cout << num1 << " x " << num2 << " = " << num1 * num2 << endl; 14 | cout << num1 << " + " << num2 << " = " << num1 + num2 << endl; 15 | 16 | cout << "Press x to exit or any other key to recalculate" << endl; 17 | cin >> userSelection; 18 | } 19 | 20 | cout << "Goodbye!" << endl; 21 | 22 | return 0; 23 | } -------------------------------------------------------------------------------- /6.12 RangeBasedFor.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | int someNums[] = { 1, 101, -1, 40, 2040 }; 8 | 9 | for (const int aNum : someNums) 10 | cout << aNum << ' '; 11 | cout << endl; 12 | 13 | for (auto anElement : { 5, 222, 110, -45, 2017 }) 14 | cout << anElement << ' '; 15 | cout << endl; 16 | 17 | char charArray[] = { 'h', 'e', 'l', 'l', 'o' }; 18 | for (auto aChar : charArray) 19 | cout << aChar << ' '; 20 | cout << endl; 21 | 22 | double moreNums[] = { 3.14, -1.3, 22, 10101 }; 23 | for (auto anElement : moreNums) 24 | cout << anElement << ' '; 25 | cout << endl; 26 | 27 | string sayHello{ "Hello World!" }; 28 | for (auto anElement : sayHello) 29 | cout << anElement << ' '; 30 | cout << endl; 31 | 32 | return 0; 33 | } -------------------------------------------------------------------------------- /6.13 MultiplyAdd_InfiniteLoop_break_continue.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | for(;;) // an empty 'for' creating an infinite loop 7 | { 8 | cout << "Enter two integers: " << endl; 9 | int num1 = 0, num2 = 0; 10 | cin >> num1; 11 | cin >> num2; 12 | 13 | cout << "Do you wish to correct the numbers? (y/n): "; 14 | char changeNumbers = '\0'; 15 | cin >> changeNumbers; 16 | 17 | if (changeNumbers == 'y') 18 | continue; // restart the loop! 19 | 20 | cout << num1 << " x " << num2 << " = " << num1 * num2 << endl; 21 | cout << num1 << " + " << num2 << " = " << num1 + num2 << endl; 22 | 23 | cout << "Press x to exit or any other key to recalculate" << endl; 24 | char userSelection = '\0'; 25 | cin >> userSelection; 26 | 27 | if (userSelection == 'x') 28 | break; // exit the infinite loop 29 | } 30 | 31 | cout << "Goodbye!" << endl; 32 | 33 | return 0; 34 | } -------------------------------------------------------------------------------- /6.14 CrossMultiplyTwoArrays_NestedLoops.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | const int ARRAY1_LEN = 3; 7 | const int ARRAY2_LEN = 2; 8 | 9 | int myNums1[ARRAY1_LEN] = {35, -3, 0}; 10 | int myNums2[ARRAY2_LEN] = {20, -1}; 11 | 12 | cout << "Multiplying each int in myNums1 by each in myNums2:" << endl; 13 | 14 | for(int index1 = 0; index1 < ARRAY1_LEN; ++index1) 15 | for(int index2 = 0; index2 < ARRAY2_LEN; ++index2) 16 | cout << myNums1[index1] << " x " << myNums2[index2] \ 17 | << " = " << myNums1[index1] * myNums2[index2] << endl; 18 | 19 | return 0; 20 | } -------------------------------------------------------------------------------- /6.15 IteratingMDArrays_nested_loops.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | const int NUM_ROWS = 3; 7 | const int NUM_COLUMNS = 4; 8 | 9 | // 2D array of integers 10 | int MyInts[NUM_ROWS][NUM_COLUMNS] = { {34, -1, 879, 22}, 11 | {24, 365, -101, -1}, 12 | {-20, 40, 90, 97} }; 13 | 14 | // iterate rows, each array of int 15 | for (int row = 0; row < NUM_ROWS; ++row) 16 | { 17 | // iterate integers in each row (columns) 18 | for (int column = 0; column < NUM_COLUMNS; ++column) 19 | { 20 | cout << "Integer[" << row << "][" << column \ 21 | << "] = " << MyInts[row][column] << endl; 22 | } 23 | } 24 | 25 | return 0; 26 | } -------------------------------------------------------------------------------- /6.16 FibonacciSeries_usingLoops.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | const int numsToCalculate = 5; 7 | cout << "This program will calculate " << numsToCalculate \ 8 | << " Fibonacci Numbers at a time" << endl; 9 | 10 | int num1 = 0, num2 = 1; 11 | char wantMore = '\0'; 12 | cout << num1 << " " << num2 << " "; 13 | 14 | do 15 | { 16 | for (int counter = 0; counter < numsToCalculate; ++counter) 17 | { 18 | cout << num1 + num2 << " "; 19 | 20 | int num2Temp = num2; 21 | num2 = num1 + num2; 22 | num1 = num2Temp; 23 | } 24 | 25 | cout << endl << "Do you want more numbers (y/n)? "; 26 | cin >> wantMore; 27 | }while (wantMore == 'y'); 28 | 29 | cout << "Goodbye!" << endl; 30 | 31 | return 0; 32 | } -------------------------------------------------------------------------------- /6.2 checkbounds.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | cout << "Enter a line of text: " << endl; 8 | string userInput; 9 | getline (cin, userInput); 10 | 11 | char copyInput[20] = {}; 12 | if (userInput.length() < 20) // check bounds 13 | { 14 | cout << "Input within bounds, creating copy" << endl; 15 | userInput.copy (copyInput, userInput.length()); 16 | cout << "copyInput contains: " << copyInput << endl; 17 | } 18 | else 19 | cout << "Bounds exceeded: cannot copy!" << endl; 20 | 21 | return 0; 22 | } -------------------------------------------------------------------------------- /6.3 Nested_if_check_Divisor.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | cout << "Enter two numbers: " << endl; 7 | float num1 = 0, num2 = 0; 8 | cin >> num1; 9 | cin >> num2; 10 | 11 | cout << "Enter 'd' to divide, anything else to multiply: "; 12 | char userSelection = '\0'; 13 | cin >> userSelection; 14 | 15 | if (userSelection == 'd') 16 | { 17 | cout << "You wish to divide!" << endl; 18 | if (num2 != 0) 19 | cout << num1 << " / " << num2 << " = " << num1 / num2 << endl; 20 | else 21 | cout << "Division by zero is not allowed" << endl; 22 | } 23 | else 24 | { 25 | cout << "You wish to multiply!" << endl; 26 | cout << num1 << " x " << num2 << " = " << num1 * num2 << endl; 27 | } 28 | 29 | return 0; 30 | } -------------------------------------------------------------------------------- /6.4 WhatDaysOfWeekMean_if_else.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | enum DaysOfWeek 7 | { 8 | Sunday = 0, 9 | Monday, 10 | Tuesday, 11 | Wednesday, 12 | Thursday, 13 | Friday, 14 | Saturday 15 | }; 16 | 17 | cout << "Find what days of the week are named after!" << endl; 18 | cout << "Enter a number for a day (Sunday = 0): "; 19 | 20 | int dayInput = Sunday; // Initialize to Sunday 21 | cin >> dayInput; 22 | 23 | if (dayInput == Sunday) 24 | cout << "Sunday was named after the Sun" << endl; 25 | else if (dayInput == Monday) 26 | cout << "Monday was named after the Moon" << endl; 27 | else if (dayInput == Tuesday) 28 | cout << "Tuesday was named after Mars" << endl; 29 | else if (dayInput == Wednesday) 30 | cout << "Wednesday was named after Mercury" << endl; 31 | else if (dayInput == Thursday) 32 | cout << "Thursday was named after Jupiter" << endl; 33 | else if (dayInput == Friday) 34 | cout << "Friday was named after Venus" << endl; 35 | else if (dayInput == Saturday) 36 | cout << "Saturday was named after Saturn" << endl; 37 | else 38 | cout << "Wrong input, execute again" << endl; 39 | 40 | return 0; 41 | } -------------------------------------------------------------------------------- /6.6 ConditionalOperator_TernaryOperator.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | cout << "Enter two numbers" << endl; 7 | int num1 = 0, num2 = 0; 8 | cin >> num1; 9 | cin >> num2; 10 | 11 | // using the ternary operator ?: 12 | int max = (num1 > num2)? num1 : num2; 13 | 14 | cout << "The greater of " << num1 << " and " \ 15 | << num2 << " is: " << max << endl; 16 | 17 | return 0; 18 | } -------------------------------------------------------------------------------- /6.7 MultiplyOrAdd_goto.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | Start: 7 | int Num1 = 0, Num2 = 0; 8 | 9 | cout << "Enter two integers: " << endl; 10 | cin >> Num1; 11 | cin >> Num2; 12 | 13 | cout << Num1 << " x " << Num2 << " = " << Num1 * Num2 << endl; 14 | cout << Num1 << " + " << Num2 << " = " << Num1 + Num2 << endl; 15 | 16 | cout << "Do you wish to perform another operation (y/n)?" << endl; 17 | char repeat = 'y'; 18 | cin >> repeat; 19 | 20 | if (repeat == 'y') 21 | goto Start; 22 | 23 | cout << "Goodbye!" << endl; 24 | 25 | return 0; 26 | } -------------------------------------------------------------------------------- /6.8 MultiplyOrAdd_while.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | char userSelection = 'm'; // initial value 7 | 8 | while (userSelection != 'x') 9 | { 10 | cout << "Enter the two integers: " << endl; 11 | int num1 = 0, num2 = 0; 12 | cin >> num1; 13 | cin >> num2; 14 | 15 | cout << num1 << " x " << num2 << " = " << num1 * num2 << endl; 16 | cout << num1 << " + " << num2 << " = " << num1 + num2 << endl; 17 | 18 | cout << "Press x to exit(x) or any other key to recalculate" << endl; 19 | cin >> userSelection; 20 | } 21 | 22 | cout << "Goodbye!" << endl; 23 | 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /6.9 MultiplyAdd_do_while.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | char userSelection = 'x'; // initial value 7 | do 8 | { 9 | cout << "Enter the two integers: " << endl; 10 | int num1 = 0, num2 = 0; 11 | cin >> num1; 12 | cin >> num2; 13 | 14 | cout << num1 << " x " << num2 << " = " << num1 * num2 << endl; 15 | cout << num1 << " + " << num2 << " = " << num1 + num2 << endl; 16 | 17 | cout << "Press x to exit(x) or any other key to recalculate" << endl; 18 | cin >> userSelection; 19 | } while (userSelection != 'x'); 20 | 21 | cout << "Goodbye!" << endl; 22 | 23 | return 0; 24 | } -------------------------------------------------------------------------------- /6.Ex1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | const int ARRAY_LEN = 5; 7 | int myNums[ARRAY_LEN]= {-55, 45, 9889, 0, 45}; 8 | 9 | for (int index = ARRAY_LEN - 1; index >= 0; --index) 10 | cout << "myNums[" << index << "] = " << myNums[index] << endl; 11 | 12 | return 0; 13 | } -------------------------------------------------------------------------------- /6.Ex2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | const int ARRAY1_LEN = 3; 7 | const int ARRAY2_LEN = 2; 8 | 9 | int myNums1[ARRAY1_LEN] = {35, -3, 0}; 10 | int MyInts2[ARRAY2_LEN] = {20, -1}; 11 | 12 | cout << "Adding each int in myNums1 by each in MyInts2:" << endl; 13 | 14 | for(int index1 = ARRAY1_LEN - 1; index1 >= 0; --index1) 15 | for(int index2 = ARRAY2_LEN - 1; index2 >= 0; --index2) 16 | cout << myNums1[index1] << " + " << MyInts2[index2] \ 17 | << " = " << myNums1[index1] + MyInts2[index2] << endl; 18 | 19 | return 0; 20 | } -------------------------------------------------------------------------------- /6.Ex3.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | cout << "How many Fibonacci numbers you wish to calculate: "; 7 | int numsToCal = 0; 8 | cin >> numsToCal; 9 | 10 | cout << "This program will calculate " << numsToCal \ 11 | << " Fibonacci Numbers at a time" << endl; 12 | 13 | int num1 = 0, num2 = 1; 14 | char wantMore = '\0'; 15 | cout << num1 << " " << num2 << " "; 16 | 17 | do 18 | { 19 | for (int index = 0; index < numsToCal; ++index) 20 | { 21 | cout << num1 + num2 << " "; 22 | 23 | int num2Temp = num2; 24 | num2 = num1 + num2; 25 | num1 = num2Temp; 26 | } 27 | 28 | cout << endl << "Do you want more numbers (y/n)? "; 29 | cin >> wantMore; 30 | }while (wantMore == 'y'); 31 | 32 | cout << "Goodbye!" << endl; 33 | 34 | return 0; 35 | } -------------------------------------------------------------------------------- /7.1 Functions_ComputingAreaCircumference.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | const double Pi = 3.14159265; 5 | 6 | // Function Declarations (Prototypes) 7 | double Area(double radius); 8 | double Circumference(double radius); 9 | 10 | int main() 11 | { 12 | cout << "Enter radius: "; 13 | double radius = 0; 14 | cin >> radius; 15 | 16 | // Call function "Area" 17 | cout << "Area is: " << Area(radius) << endl; 18 | 19 | // Call function "Circumference" 20 | cout << "Circumference is: " << Circumference(radius) << endl; 21 | 22 | return 0; 23 | } 24 | 25 | // Function definitions (implementations) 26 | double Area(double radius) 27 | { 28 | return Pi * radius * radius; 29 | } 30 | 31 | double Circumference(double radius) 32 | { 33 | return 2 * Pi * radius; 34 | } -------------------------------------------------------------------------------- /7.10 Functions_Inline.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // define an inline function that doubles 5 | inline long DoubleNum (int inputNum) 6 | { 7 | return inputNum * 2; 8 | } 9 | 10 | int main() 11 | { 12 | cout << "Enter an integer: "; 13 | int inputNum = 0; 14 | cin >> inputNum; 15 | 16 | // Call inline function 17 | cout << "Double is: " << DoubleNum(inputNum) << endl; 18 | 19 | return 0; 20 | } 21 | -------------------------------------------------------------------------------- /7.11 auto function return.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | const double Pi = 3.14159265; 5 | 6 | auto Area(double radius) 7 | { 8 | return Pi * radius * radius; 9 | } 10 | 11 | int main() 12 | { 13 | cout << "Enter radius: "; 14 | double radius = 0; 15 | cin >> radius; 16 | 17 | // Call function "Area" 18 | cout << "Area is: " << Area(radius) << endl; 19 | 20 | return 0; 21 | } -------------------------------------------------------------------------------- /7.12 Functions_Lambda.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | void DisplayNums(vector& dynArray) 7 | { 8 | for_each (dynArray.begin(), dynArray.end(), \ 9 | [](int Element) {cout << Element << " ";} ); 10 | 11 | cout << endl; 12 | } 13 | 14 | int main() 15 | { 16 | vector myNums; 17 | myNums.push_back(501); 18 | myNums.push_back(-1); 19 | myNums.push_back(25); 20 | myNums.push_back(-35); 21 | 22 | DisplayNums(myNums); 23 | 24 | cout << "Sorting them in descending order" << endl; 25 | 26 | sort (myNums.begin(), myNums.end(), 27 | [](int Num1, int Num2) {return (Num2 < Num1); } ); 28 | 29 | DisplayNums(myNums); 30 | 31 | return 0; 32 | } -------------------------------------------------------------------------------- /7.2 Functions_MultipleParameters_Cylinder.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | const double Pi = 3.14159265; 5 | 6 | // Declaration contains two parameters 7 | double SurfaceArea(double radius, double height); 8 | 9 | int main() 10 | { 11 | cout << "Enter the radius of the cylinder: "; 12 | double radius = 0; 13 | cin >> radius; 14 | cout << "Enter the height of the cylinder: "; 15 | double height = 0; 16 | cin >> height; 17 | 18 | cout << "Surface area: " << SurfaceArea(radius, height) << endl; 19 | 20 | return 0; 21 | } 22 | 23 | double SurfaceArea(double radius, double height) 24 | { 25 | double area = 2 * Pi * radius * radius + 2 * Pi * radius * height; 26 | return area; 27 | } -------------------------------------------------------------------------------- /7.3 Functions_SayingHelloWithoutParamsReturnValue.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void SayHello(); 5 | 6 | int main() 7 | { 8 | SayHello(); 9 | return 0; 10 | } 11 | 12 | void SayHello() 13 | { 14 | cout << "Hello World" << endl; 15 | return; // an empty return 16 | } -------------------------------------------------------------------------------- /7.4 Functions_DefaulParameters_Pi.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Function declaration with default argument 5 | double Area(double radius, double pi = 3.14); 6 | 7 | int main() 8 | { 9 | cout << "Enter radius: "; 10 | double radius = 0; 11 | cin >> radius; 12 | 13 | cout << "pi is 3.14, do you wish to change this (y / n)? "; 14 | char changePi = 'n'; 15 | cin >> changePi; 16 | 17 | double circleArea = 0; 18 | if (changePi == 'y') 19 | { 20 | cout << "Enter new pi: "; 21 | double newPi = 3.14; 22 | cin >> newPi; 23 | circleArea = Area (radius, newPi); 24 | } 25 | else 26 | circleArea = Area(radius); // Ignore 2nd param, use default value 27 | 28 | // Call function "Area" 29 | cout << "Area is: " << circleArea << endl; 30 | 31 | return 0; 32 | } 33 | 34 | // Function definitions (implementations) 35 | double Area(double radius, double pi) 36 | { 37 | return pi * radius * radius; 38 | } -------------------------------------------------------------------------------- /7.5 Functions_Recursive_Fibonacci.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int GetFibNumber(int fibIndex) 5 | { 6 | if (fibIndex < 2) 7 | return fibIndex; 8 | else // recursion if fibIndex >= 2 9 | return GetFibNumber(fibIndex - 1) + GetFibNumber(fibIndex - 2); 10 | } 11 | 12 | int main() 13 | { 14 | cout << "Enter 0-based index of desired Fibonacci Number: "; 15 | int index = 0; 16 | cin >> index; 17 | 18 | cout << "Fibonacci number is: " << GetFibNumber(index) << endl; 19 | return 0; 20 | } -------------------------------------------------------------------------------- /7.6 Functions_MultipleReturns.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | const double Pi = 3.14159265; 4 | 5 | void QueryAndCalculate() 6 | { 7 | cout << "Enter radius: "; 8 | double radius = 0; 9 | cin >> radius; 10 | 11 | cout << "Area: " << Pi * radius * radius << endl; 12 | 13 | cout << "Do you wish to calculate circumference (y/n)? "; 14 | char calcCircum = 'n'; 15 | cin >> calcCircum; 16 | 17 | if (calcCircum == 'n') 18 | return; 19 | 20 | cout << "Circumference: " << 2 * Pi * radius << endl; 21 | return; 22 | } 23 | 24 | int main() 25 | { 26 | QueryAndCalculate (); 27 | 28 | return 0; 29 | } -------------------------------------------------------------------------------- /7.7 Functions_Overloaded_Area_CyclinderCircle.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | const double Pi = 3.14159265; 5 | 6 | double Area(double radius); // for circle 7 | double Area(double radius, double height); // overloaded for cylinder 8 | 9 | int main() 10 | { 11 | cout << "Enter z for Cylinder, c for Circle: "; 12 | char userSelection = 'z'; 13 | cin >> userSelection; 14 | 15 | cout << "Enter radius: "; 16 | double radius = 0; 17 | cin >> radius; 18 | 19 | if (userSelection == 'z') 20 | { 21 | cout << "Enter height: "; 22 | double height = 0; 23 | cin >> height; 24 | 25 | // Invoke overloaded variant of Area for cylinder 26 | cout << "Area of cylinder is: " << Area (radius, height) << endl; 27 | } 28 | else 29 | cout << "Area of circle is: " << Area (radius) << endl; 30 | 31 | return 0; 32 | } 33 | 34 | // for circle 35 | double Area(double radius) 36 | { 37 | return Pi * radius * radius; 38 | } 39 | 40 | // overloaded for cylinder 41 | double Area(double radius, double height) 42 | { 43 | // reuse the area of circle 44 | return 2 * Area (radius) + 2 * Pi * radius * height; 45 | } -------------------------------------------------------------------------------- /7.8 Functions_Passing_Arrays.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void DisplayArray(int numbers[], int length) 5 | { 6 | for (int index = 0; index < length; ++index) 7 | cout << numbers[index] << " "; 8 | 9 | cout << endl; 10 | } 11 | 12 | void DisplayArray(char characters[], int length) 13 | { 14 | for (int index = 0; index < length; ++index) 15 | cout << characters[index] << " "; 16 | 17 | cout << endl; 18 | } 19 | 20 | int main() 21 | { 22 | int myNumbers[4] = {24, 58, -1, 245}; 23 | DisplayArray(myNumbers, 4); 24 | 25 | char myStatement[7] = {'H', 'e', 'l', 'l', 'o', '!', '\0'}; 26 | DisplayArray(myStatement, 7); 27 | 28 | return 0; 29 | } -------------------------------------------------------------------------------- /7.9 Functions_PassingReference.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | const double Pi = 3.1416; 5 | 6 | // output parameter result by reference 7 | void Area(double radius, double& result) 8 | { 9 | result = Pi * radius * radius; 10 | } 11 | 12 | int main() 13 | { 14 | cout << "Enter radius: "; 15 | double radius = 0; 16 | cin >> radius; 17 | 18 | double areaFetched = 0; 19 | Area(radius, areaFetched); 20 | 21 | cout << "The area is: " << areaFetched << endl; 22 | return 0; 23 | } -------------------------------------------------------------------------------- /8.1 Pointers_ReferencingOperator.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int age = 30; 7 | const double Pi = 3.1416; 8 | 9 | // Use & to find the address in memory 10 | cout << "Integer age is located at: 0x" << &age << endl; 11 | cout << "Double Pi is located at: 0x" << &Pi << endl; 12 | 13 | return 0; 14 | } -------------------------------------------------------------------------------- /8.10 Pointers_const_calculatingsquare.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void CalcArea(const double* const ptrPi, // const pointer to const data 5 | const double* const ptrRadius, // i.e. no changes allowed 6 | double* const ptrArea) // can change data pointed to 7 | { 8 | // check pointers for validity before using! 9 | if (ptrPi && ptrRadius && ptrArea) 10 | *ptrArea = (*ptrPi) * (*ptrRadius) * (*ptrRadius); 11 | } 12 | 13 | int main() 14 | { 15 | const double Pi = 3.1416; 16 | 17 | cout << "Enter radius of circle: "; 18 | double radius = 0; 19 | cin >> radius; 20 | 21 | double area = 0; 22 | CalcArea (&Pi, &radius, &area); 23 | 24 | cout << "Area is = " << area << endl; 25 | 26 | return 0; 27 | } -------------------------------------------------------------------------------- /8.11 Pointers_ArrayVar_IsAddressOfFirst.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | // Static array of 5 integers 7 | int myNumbers[5]; 8 | 9 | // Pointer initialized to array 10 | int* pointToNums = myNumbers; 11 | 12 | // Display address contained in pointer 13 | cout << "pointToNums = 0x" << hex << pointToNums << endl; 14 | 15 | // Address of first element of array 16 | cout << "&myNumbers[0] = 0x" << hex << &myNumbers[0] << endl; 17 | 18 | return 0; 19 | } -------------------------------------------------------------------------------- /8.12 Pointers_Arrays_Similarities.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | const int ARRAY_LEN = 5; 7 | 8 | // Static array of 5 integers, initialized 9 | int myNumbers[ARRAY_LEN] = {24, -1, 365, -999, 2011}; 10 | 11 | // Pointer initialized to first element in array 12 | int* pointToNums = myNumbers; 13 | 14 | cout << "Display array using pointer syntax, operator* \n"; 15 | for (int index = 0; index < ARRAY_LEN; ++index) 16 | cout << "Element "<> userInput; 12 | 13 | if (userInput == 'y') 14 | { 15 | isSunny = new bool; 16 | *isSunny = true; 17 | } 18 | 19 | // isSunny contains invalid value if user entered 'n' 20 | cout << "Boolean flag sunny says: " << *isSunny << endl; 21 | 22 | // delete being invoked, even when new wasn't 23 | delete isSunny; 24 | 25 | return 0; 26 | } -------------------------------------------------------------------------------- /8.14 Pointers_BetterProgramming.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | cout << "Is it sunny (y/n)? "; 7 | char userInput = 'y'; 8 | cin >> userInput; 9 | 10 | // declare pointer and initialize 11 | bool* const isSunny = new bool; 12 | *isSunny = true; 13 | 14 | if (userInput == 'n') 15 | *isSunny = false; 16 | 17 | cout << "Boolean flag sunny says: " << *isSunny << endl; 18 | 19 | // release valid memory 20 | delete isSunny; 21 | 22 | return 0; 23 | } -------------------------------------------------------------------------------- /8.15 CrashesNewWithoutExcHandler.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // uncomment the try-catch block to avoid crash 5 | int main() 6 | { 7 | //try 8 | { 9 | // Request a LOT of memory! 10 | int* pointsToManyNums = new int[0x1fffffff]; 11 | 12 | // Use the allocated memory 13 | delete[] pointsToManyNums; 14 | } 15 | //catch (bad_alloc) 16 | { 17 | cout << "Memory allocation failed. Ending program" << endl; 18 | } 19 | return 0; 20 | } -------------------------------------------------------------------------------- /8.15 Pointers_new_exceptionhandler.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // remove the try-catch block to see this application crash 5 | int main() 6 | { 7 | try 8 | { 9 | // Request a LOT of memory! 10 | int* pointsToManyNums = new int [0x1fffffff]; 11 | 12 | // Use the allocated memory 13 | delete[] pointsToManyNums; 14 | } 15 | catch (bad_alloc) 16 | { 17 | cout << "Memory allocation failed. Ending program" << endl; 18 | } 19 | return 0; 20 | } -------------------------------------------------------------------------------- /8.16 Pointers_new_nothrow.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | // Request LOTS of memory space, use nothrow 7 | int* pointsToManyNums = new(nothrow) int [0x1fffffff]; 8 | 9 | if (pointsToManyNums) // check pointsToManyNums != NULL 10 | { 11 | // Use the allocated memory 12 | delete[] pointsToManyNums; 13 | } 14 | else 15 | cout << "Memory allocation failed. Ending program" << endl; 16 | 17 | return 0; 18 | } -------------------------------------------------------------------------------- /8.17 References_Declaring_Initializing.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int original = 30; 7 | cout << "original = " << original << endl; 8 | cout << "original is at address: " << hex << &original << endl; 9 | 10 | int& ref1 = original; 11 | cout << "ref1 is at address: " << hex << &ref1 << endl; 12 | 13 | int& ref2 = ref1; 14 | cout << "ref2 is at address: " << hex << &ref2 << endl; 15 | cout << "Therefore, ref2 = " << dec << ref2 << endl; 16 | 17 | return 0; 18 | } -------------------------------------------------------------------------------- /8.18 References_PassingArgsToFunctions.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void Square(int& number) 5 | { 6 | number *= number; 7 | } 8 | 9 | int main() 10 | { 11 | cout << "Enter a number you wish to square: "; 12 | int number = 0; 13 | cin >> number; 14 | 15 | Square(number); 16 | cout << "Square is: " << number << endl; 17 | 18 | return 0; 19 | } -------------------------------------------------------------------------------- /8.19 References_Const.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void Square(const int& number, int& result) 5 | { 6 | result = number*number; 7 | } 8 | 9 | int main() 10 | { 11 | cout << "Enter a number you wish to square: "; 12 | int number = 0; 13 | cin >> number; 14 | 15 | int square = 0; 16 | Square(number, square); 17 | cout << "Square of " << number << " = " << square << endl; 18 | 19 | return 0; 20 | } -------------------------------------------------------------------------------- /8.2 Pointers_AssigningRefToPtr.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int age = 30; 7 | int* pointsToInt = &age; 8 | 9 | // Displaying the value of pointer 10 | cout << "Integer age is at: 0x" << hex << pointsToInt << endl; 11 | 12 | return 0; 13 | } -------------------------------------------------------------------------------- /8.3 Pointers_OnePtrManyIntegers.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int age = 30; 7 | 8 | int* pointsToInt = &age; 9 | cout << "pointsToInt points to age now" << endl; 10 | 11 | // Displaying the value of pointer 12 | cout << "pointsToInt = 0x" << hex << pointsToInt << endl; 13 | 14 | int dogsAge = 9; 15 | pointsToInt = &dogsAge; 16 | cout << "pointsToInt points to dogsAge now" << endl; 17 | 18 | cout << "pointsToInt = 0x" << hex << pointsToInt << endl; 19 | 20 | return 0; 21 | } -------------------------------------------------------------------------------- /8.4 Pointers_Dereferencing_or_IndirectionOperator.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int age = 30; 7 | int dogsAge = 9; 8 | 9 | cout << "Integer age = " << age << endl; 10 | cout << "Integer dogsAge = " << dogsAge << endl; 11 | 12 | int* pointsToInt = &age; 13 | cout << "pointsToInt points to age" << endl; 14 | 15 | // Displaying the value of pointer 16 | cout << "pointsToInt = 0x" << hex << pointsToInt << endl; 17 | 18 | // Displaying the value at the pointed location 19 | cout << "*pointsToInt = " << dec << *pointsToInt << endl; 20 | 21 | pointsToInt = &dogsAge; 22 | cout << "pointsToInt points to dogsAge now" << endl; 23 | 24 | cout << "pointsToInt = 0x" << hex << pointsToInt << endl; 25 | cout << "*pointsToInt = " << dec << *pointsToInt << endl; 26 | 27 | return 0; 28 | } -------------------------------------------------------------------------------- /8.5 Pointers_AssigningUsingDerefOp.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int dogsAge = 30; 7 | cout << "Initialized dogsAge = " << dogsAge << endl; 8 | 9 | int* pointsToAnAge = &dogsAge; 10 | cout << "pointsToAnAge points to dogsAge" << endl; 11 | 12 | cout << "Enter an age for your dog: "; 13 | 14 | // store input at the memory pointed to by pointsToAnAge 15 | cin >> *pointsToAnAge; 16 | 17 | // Displaying the address where age is stored 18 | cout << "Input stored at 0x" << hex << pointsToAnAge << endl; 19 | 20 | cout << "Integer dogsAge = " << dec << dogsAge << endl; 21 | 22 | return 0; 23 | } -------------------------------------------------------------------------------- /8.6 Pointers_sizeof_Test.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | cout << "sizeof fundamental types -" << endl; 7 | cout << "sizeof(char) = " << sizeof(char) << endl; 8 | cout << "sizeof(int) = " << sizeof(int) << endl; 9 | cout << "sizeof(double) = " << sizeof(double) << endl; 10 | 11 | cout << "sizeof pointers to fundamental types -" << endl; 12 | cout << "sizeof(char*) = " << sizeof(char*) << endl; 13 | cout << "sizeof(int*) = " << sizeof(int*) << endl; 14 | cout << "sizeof(double*) = " << sizeof(double*) << endl; 15 | 16 | return 0; 17 | } -------------------------------------------------------------------------------- /8.7 Pointers_Using_new_delete.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | // Request for memory space for an int 7 | int* pointsToAnAge = new int; 8 | 9 | // Use the allocated memory to store a number 10 | cout << "Enter your dog's age: "; 11 | cin >> *pointsToAnAge; 12 | 13 | // use indirection operator* to access value 14 | cout << "Age " << *pointsToAnAge << " is stored at 0x" 15 | << hex << pointsToAnAge << endl; 16 | 17 | delete pointsToAnAge; // release memory 18 | 19 | return 0; 20 | } -------------------------------------------------------------------------------- /8.8 Pointers_Using_new_delete_char_array.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | cout << "How many integers shall I reserve memory for?" << endl; 8 | int numEntries = 0; 9 | cin >> numEntries; 10 | 11 | int* myNumbers = new int[numEntries]; 12 | 13 | cout << "Memory allocated at: 0x" << myNumbers << hex << endl; 14 | 15 | // de-allocate before exiting 16 | delete[] myNumbers; 17 | 18 | return 0; 19 | } -------------------------------------------------------------------------------- /8.9 Pointer_using_new_delete_multiple_elements.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | cout << "How many integers you wish to enter? "; 7 | int numEntries = 0; 8 | cin >> numEntries; 9 | 10 | int* pointsToInts = new int [numEntries]; 11 | 12 | cout << "Allocated for " << numEntries << " integers" << endl; 13 | for(int counter = 0; counter < numEntries; ++counter) 14 | { 15 | cout << "Enter number "<< counter << ": "; 16 | cin >> *(pointsToInts + counter); 17 | } 18 | 19 | cout << "Displaying all numbers entered: " << endl; 20 | for(int counter = 0; counter < numEntries; ++counter) 21 | cout << *(pointsToInts++) << " "; 22 | 23 | cout << endl; 24 | 25 | // return pointer to initial position 26 | pointsToInts -= numEntries; 27 | 28 | // done with using memory? release 29 | delete[] pointsToInts; 30 | 31 | return 0; 32 | } -------------------------------------------------------------------------------- /9.1 ClassHuman.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Human 6 | { 7 | public: 8 | string name; 9 | int age; 10 | 11 | void IntroduceSelf() 12 | { 13 | cout << "I am " + name << " and am "; 14 | cout << age << " years old" << endl; 15 | } 16 | }; 17 | 18 | int main() 19 | { 20 | // An object of class Human with attribute name as "Adam" 21 | Human firstMan; 22 | firstMan.name = "Adam"; 23 | firstMan.age = 30; 24 | 25 | // An object of class Human with attribute name as "Eve" 26 | Human firstWoman; 27 | firstWoman.name = "Eve"; 28 | firstWoman.age = 28; 29 | 30 | firstMan.IntroduceSelf(); 31 | firstWoman.IntroduceSelf(); 32 | } -------------------------------------------------------------------------------- /9.10 Singleton.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class President 6 | { 7 | private: 8 | President() {}; // private default constructor 9 | President(const President&); // private copy constructor 10 | const President& operator=(const President&); // assignment operator 11 | 12 | string name; 13 | 14 | public: 15 | static President& GetInstance() 16 | { 17 | // static objects are constructed only once 18 | static President onlyInstance; 19 | return onlyInstance; 20 | } 21 | 22 | string GetName() 23 | { return name; } 24 | 25 | void SetName(string InputName) 26 | { name = InputName; } 27 | }; 28 | 29 | int main() 30 | { 31 | President& onlyPresident = President::GetInstance(); 32 | onlyPresident.SetName("Abraham Lincoln"); 33 | 34 | // uncomment lines to see how compile failures prohibit duplicates 35 | // President second; // cannot access constructor 36 | // President* third= new President(); // cannot access constructor 37 | // President fourth = onlyPresident; // cannot access copy constructor 38 | // onlyPresident = President::GetInstance(); // cannot access operator= 39 | 40 | cout << "The name of the President is: "; 41 | cout << President::GetInstance().GetName() << endl; 42 | 43 | return 0; 44 | } -------------------------------------------------------------------------------- /9.11 MonsterDB_ForceConstructionOnFreeStore.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class MonsterDB 5 | { 6 | private: 7 | ~MonsterDB() {}; // private destructor prevents instances on stack 8 | 9 | public: 10 | static void DestroyInstance(MonsterDB* pInstance) 11 | { 12 | delete pInstance; // member can invoke private destructor 13 | } 14 | 15 | void DoSomething() {} // sample member method 16 | }; 17 | 18 | int main() 19 | { 20 | // MonsterDB myDB_Stack; // error - cannot instantiate on stack as designed 21 | MonsterDB* myDB = new MonsterDB(); // OK: on free store 22 | myDB->DoSomething(); 23 | 24 | // uncomment next line to see compile failure 25 | // delete myDB; // private destructor cannot be invoked 26 | 27 | // use static member to release memory 28 | MonsterDB::DestroyInstance(myDB); 29 | 30 | return 0; 31 | } -------------------------------------------------------------------------------- /9.12 explicit constructors.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Human 5 | { 6 | int age; 7 | public: 8 | // explicit constructor blocks implicit conversions 9 | explicit Human(int humansAge) : age(humansAge) {} 10 | }; 11 | 12 | void DoSomething(Human person) 13 | { 14 | cout << "Human did something" << endl; 15 | return; 16 | } 17 | 18 | int main() 19 | { 20 | Human kid(10); // explicit converion is OK 21 | Human anotherKid = Human(11); // explicit, OK 22 | DoSomething(kid); // OK 23 | 24 | // Human anotherKid = 11; // failure: implicit conversion not OK 25 | // DoSomething(10); // implicit conversion 26 | 27 | return 0; 28 | } -------------------------------------------------------------------------------- /9.13 SizeOfClass.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class MyBuffer 5 | { 6 | private: 7 | int* myNums; 8 | 9 | public: 10 | MyBuffer(unsigned int length) 11 | { 12 | myNums = new int[length]; // allocate memory 13 | } 14 | 15 | ~MyBuffer() 16 | { 17 | delete[] myNums; // free allocated memory 18 | } 19 | 20 | // other set and get functions to work with myNums 21 | }; 22 | 23 | class Human 24 | { 25 | private: 26 | int age; 27 | string gender; 28 | string name; 29 | 30 | public: 31 | Human(const string& inputName, int inputAge, string inputGender) 32 | : name(inputName), age (inputAge), gender(inputGender) {} 33 | 34 | int GetAge () 35 | { return age; } 36 | }; 37 | 38 | int main() 39 | { 40 | MyBuffer buf1(5); // buffer initialized to 5 integers 41 | MyBuffer buf2(20);// buffer initialized to 20 integers 42 | 43 | cout << "sizeof(MyBuffer) = " << sizeof(MyBuffer) << endl; 44 | cout << "sizeof(buf1) = " << sizeof(buf1) << endl; 45 | cout << "sizeof(buf2) = " << sizeof(buf2) << endl; 46 | 47 | Human firstMan("Adam", 25, "man"); 48 | Human firstWoman("Eve", 25, "woman"); 49 | 50 | cout << "sizeof(Human) = " << sizeof(Human) << endl; 51 | cout << "sizeof(firstMan) = " << sizeof(firstMan) << endl; 52 | cout << "sizeof(firstWoman) = " << sizeof(firstWoman) << endl; 53 | 54 | return 0; 55 | } -------------------------------------------------------------------------------- /9.14 FriendFunctions.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Human 6 | { 7 | private: 8 | friend void DisplayAge(const Human& person); 9 | string name; 10 | int age; 11 | 12 | public: 13 | Human(string humansName, int humansAge) 14 | { 15 | name = humansName; 16 | age = humansAge; 17 | } 18 | }; 19 | 20 | void DisplayAge(const Human& person) 21 | { 22 | cout << person.age << endl; 23 | } 24 | 25 | int main() 26 | { 27 | Human firstMan("Adam", 25); 28 | cout << "Accessing private member age via friend function: "; 29 | DisplayAge(firstMan); 30 | 31 | return 0; 32 | } -------------------------------------------------------------------------------- /9.15 FriendClass.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Human 6 | { 7 | private: 8 | friend class Utility; 9 | string name; 10 | int age; 11 | 12 | public: 13 | Human(string humansName, int humansAge) 14 | { 15 | name = humansName; 16 | age = humansAge; 17 | } 18 | }; 19 | 20 | class Utility 21 | { 22 | public: 23 | static void DisplayAge(const Human& person) 24 | { 25 | cout << person.age << endl; 26 | } 27 | }; 28 | 29 | int main() 30 | { 31 | Human firstMan("Adam", 25); 32 | cout << "Accessing private member age via friend class: "; 33 | Utility::DisplayAge(firstMan); 34 | 35 | return 0; 36 | } -------------------------------------------------------------------------------- /9.16 UsingUnions.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | union SimpleUnion 5 | { 6 | int num; 7 | char alphabet; 8 | }; 9 | 10 | struct ComplexType 11 | { 12 | enum class DataType 13 | { 14 | Int, 15 | Char 16 | } Type; 17 | 18 | union Value 19 | { 20 | int num; 21 | char alphabet; 22 | 23 | Value() {} 24 | ~Value() {} 25 | }value; 26 | }; 27 | 28 | void DisplayComplexType(const ComplexType& obj) 29 | { 30 | switch (obj.Type) 31 | { 32 | case ComplexType::DataType::Int: 33 | cout << "Union contains number: " << obj.value.num << endl; 34 | break; 35 | 36 | case ComplexType::DataType::Char: 37 | cout << "Union contains character: " << obj.value.alphabet << endl; 38 | break; 39 | } 40 | } 41 | 42 | int main() 43 | { 44 | SimpleUnion u1, u2; 45 | u1.num = 2100; 46 | u2.alphabet = 'C'; 47 | 48 | cout << "sizeof(u1) containing integer: " << sizeof(u1) << endl; 49 | cout << "sizeof(u2) containing character: " << sizeof(u2) << endl; 50 | 51 | ComplexType myData1, myData2; 52 | myData1.Type = ComplexType::DataType::Int; 53 | myData1.value.num = 2017; 54 | 55 | myData2.Type = ComplexType::DataType::Char; 56 | myData2.value.alphabet = 'X'; 57 | 58 | DisplayComplexType(myData1); 59 | DisplayComplexType(myData2); 60 | 61 | return 0; 62 | } -------------------------------------------------------------------------------- /9.17 AggregateInitializationClasses.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Aggregate1 6 | { 7 | public: 8 | int num; 9 | double pi; 10 | }; 11 | 12 | struct Aggregate2 13 | { 14 | char hello[6]; 15 | int impYears[3]; 16 | string world; 17 | }; 18 | 19 | int main() 20 | { 21 | int myNums[] = { 9, 5, -1 }; // myNums is int[3] 22 | Aggregate1 a1{ 2023, 3.14 }; 23 | cout << "Pi is approximately: " << a1.pi << endl; 24 | 25 | Aggregate2 a2{ {'h', 'e', 'l', 'l', 'o'}, {2017, 2020, 2023}, "world"}; 26 | 27 | // Alternatively 28 | Aggregate2 a2_2{'h', 'e', 'l', 'l', 'o', '\0', 2017, 2020, 2023, "world"}; 29 | 30 | cout << a2.hello << ' ' << a2.world << endl; 31 | cout << "C++ standard update scheduled in: " << a2.impYears[2] << endl; 32 | 33 | return 0; 34 | } -------------------------------------------------------------------------------- /9.18 constexpr class.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Human 5 | { 6 | int age; 7 | public: 8 | constexpr Human(int humansAge) :age(humansAge) {} 9 | constexpr int GetAge() const { return age; } 10 | }; 11 | 12 | int main() 13 | { 14 | constexpr Human somePerson(15); 15 | const int hisAge = somePerson.GetAge(); 16 | 17 | Human anotherPerson(45); // not constant expression 18 | 19 | return 0; 20 | } -------------------------------------------------------------------------------- /9.2 DemonstratesAbstraction_HidesTrueAge.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Human 5 | { 6 | private: 7 | // Private member data: 8 | int age; 9 | 10 | public: 11 | void SetAge(int inputAge) 12 | { 13 | age = inputAge; 14 | } 15 | 16 | // Human lies about his / her age (if over 30) 17 | int GetAge() 18 | { 19 | if (age > 30) 20 | return (age - 2); 21 | else 22 | return age; 23 | } 24 | }; 25 | 26 | int main() 27 | { 28 | Human firstMan; 29 | firstMan.SetAge(35); 30 | 31 | Human firstWoman; 32 | firstWoman.SetAge(22); 33 | 34 | cout << "Age of firstMan " << firstMan.GetAge() << endl; 35 | cout << "Age of firstWoman " << firstWoman.GetAge() << endl; 36 | 37 | return 0; 38 | } -------------------------------------------------------------------------------- /9.3 ClassWithConstructors.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Human 6 | { 7 | private: 8 | string name; 9 | int age; 10 | 11 | public: 12 | Human() // constructor 13 | { 14 | age = 1; // initialization 15 | cout << "Constructed an instance of class Human" << endl; 16 | } 17 | 18 | void SetName (string humansName) 19 | { 20 | name = humansName; 21 | } 22 | 23 | void SetAge(int humansAge) 24 | { 25 | age = humansAge; 26 | } 27 | 28 | void IntroduceSelf() 29 | { 30 | cout << "I am " + name << " and am "; 31 | cout << age << " years old" << endl; 32 | } 33 | }; 34 | 35 | int main() 36 | { 37 | Human firstWoman; 38 | firstWoman.SetName("Eve"); 39 | firstWoman.SetAge (28); 40 | 41 | firstWoman.IntroduceSelf(); 42 | } -------------------------------------------------------------------------------- /9.4 Overloaded Constructors.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Human 6 | { 7 | private: 8 | string name; 9 | int age; 10 | 11 | public: 12 | Human() // default constructor 13 | { 14 | age = 0; // initialized to ensure no junk value 15 | cout << "Default constructor: name and age not set" << endl; 16 | } 17 | 18 | Human(string humansName, int humansAge) // overloaded constructor 19 | { 20 | name = humansName; 21 | age = humansAge; 22 | cout << "Overloaded constructor creates "; 23 | cout << name << " of " << age << " years" << endl; 24 | } 25 | }; 26 | 27 | int main() 28 | { 29 | Human firstMan; // use default constructor 30 | Human firstWoman ("Eve", 20); // use overloaded constructor 31 | } -------------------------------------------------------------------------------- /9.5 OnlyOverloadedConstructor_NoDefault.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Human 6 | { 7 | private: 8 | string name; 9 | int age; 10 | 11 | public: 12 | Human(string humansName /*= "Adam"*/, int humansAge /*= 25*/) 13 | { 14 | name = humansName; 15 | age = humansAge; 16 | cout << "Overloaded constructor creates " << name; 17 | cout << " of age " << age << endl; 18 | } 19 | 20 | void IntroduceSelf() 21 | { 22 | cout << "I am " + name << " and am "; 23 | cout << age << " years old" << endl; 24 | } 25 | }; 26 | 27 | int main() 28 | { 29 | Human firstMan("Adam", 25); 30 | Human firstWoman("Eve", 28); 31 | 32 | firstMan.IntroduceSelf(); 33 | firstWoman.IntroduceSelf(); 34 | } -------------------------------------------------------------------------------- /9.6 Constructor_InitializationLists.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Human 6 | { 7 | private: 8 | int age; 9 | string name; 10 | 11 | public: 12 | Human(string humansName = "Adam", int humansAge = 25) 13 | :name(humansName), age(humansAge) 14 | { 15 | cout << "Constructed a human called " << name; 16 | cout << ", " << age << " years old" << endl; 17 | } 18 | }; 19 | 20 | int main() 21 | { 22 | Human adam; 23 | Human eve("Eve", 18); 24 | 25 | return 0; 26 | } -------------------------------------------------------------------------------- /9.7 FreeMemInDestructor.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class MyBuffer 5 | { 6 | private: 7 | int* myNums; 8 | 9 | public: 10 | MyBuffer(unsigned int length) 11 | { 12 | cout << "Constructor allocates " << length << " integers" << endl; 13 | myNums = new int[length]; // allocate memory 14 | } 15 | 16 | ~MyBuffer() 17 | { 18 | cout << "Destructor releasing allocated memory" << endl; 19 | delete[] myNums; // free allocated memory 20 | } 21 | 22 | // other set and get functions to work with myNums 23 | }; 24 | 25 | int main() 26 | { 27 | cout << "How many integers would you like to store? "; 28 | unsigned int numsToStore = 0; 29 | cin >> numsToStore; 30 | 31 | MyBuffer buf(numsToStore); 32 | 33 | return 0; 34 | } -------------------------------------------------------------------------------- /9.8 ShallowCopy.cpp: -------------------------------------------------------------------------------- 1 | // This sample involves shallow copying and will crash to demonstrate the problem 2 | #include 3 | using namespace std; 4 | 5 | class MyBuffer 6 | { 7 | private: 8 | int* myNums; 9 | 10 | public: 11 | MyBuffer(unsigned int length) 12 | { 13 | cout << "Constructor allocates " << length << " integers" << endl; 14 | myNums = new int[length]; // allocate memory 15 | } 16 | 17 | ~MyBuffer() 18 | { 19 | cout << "Destructor releasing allocated memory" << endl; 20 | delete[] myNums; // free allocated memory 21 | } 22 | 23 | // other set and get functions to work with myNums 24 | }; 25 | 26 | void UseMyBuf(MyBuffer copyBuf) 27 | { 28 | cout << "Copy of buf will be destroyed when function ends" << endl; 29 | } 30 | 31 | int main() 32 | { 33 | cout << "How many integers would you like to store? "; 34 | unsigned int numsToStore = 0; 35 | cin >> numsToStore; 36 | 37 | MyBuffer buf(numsToStore); 38 | UseMyBuf(buf); // send a copy 39 | 40 | return 0; // crash, at destruction of buf 41 | } -------------------------------------------------------------------------------- /9.Ex3.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Human 6 | { 7 | int Age; 8 | string Name; 9 | 10 | public: 11 | Human(string InputName, int InputAge) 12 | : Name(InputName), Age(InputAge) {} 13 | }; 14 | 15 | int main() 16 | { 17 | Human FirstMan("Adam", 24); 18 | return 0; 19 | } -------------------------------------------------------------------------------- /9.Ex4 Circle.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Circle 5 | { 6 | const double Pi; 7 | double Radius; 8 | 9 | public: 10 | Circle(double InputRadius) : Radius(InputRadius), Pi(3.1416) {} 11 | 12 | double GetCircumference() 13 | { 14 | return 2*Pi*Radius; 15 | } 16 | 17 | double GetArea() 18 | { 19 | return Pi*Radius*Radius; 20 | } 21 | }; 22 | 23 | int main() 24 | { 25 | cout << "Enter a radius: "; 26 | double Radius = 0; 27 | cin >> Radius; 28 | 29 | Circle myCircle(Radius); 30 | 31 | cout << "Circumference = " << myCircle.GetCircumference() << endl; 32 | cout << "Area = " << myCircle.GetArea() << endl; 33 | 34 | return 0; 35 | } --------------------------------------------------------------------------------