Modern C++ Overview
Part One Exercises
Copyright © James Raynard 2023
Universal Initialization
• Write a program that uses universal initialization to define the
following variables
• x, type int, initial value 7
• str, type std::string, initial value "Let us begin"
• y, type int, initial value 7.7
• Why does the definition of y not compile? Try again with the
traditional form of initialization
• Display the values of x, str, and y
• Test and run your program
Copyright © James Raynard 2023
Universal Initialization contd
• Still using universal initialization, add the following variable to your
program
• vec, type std::vector of int, values 4, 2, 3, 5, 1
• Print out the elements of vec
• Test and run your program
Copyright © James Raynard 2023
nullptr
• Describe the nullptr feature
• Write two overloaded functions, one taking an int by value and one
taking pointer to int. Each function displays the type of its argument
• Write a program which makes two calls to the function, one with
argument NULL and one with argument nullptr
• Run your program. Explain your observations
Copyright © James Raynard 2023
std::chrono
• Using C++11 syntax, write down expressions which represent intervals
of
• 2 seconds
• 20 milliseconds
• 50 microseconds
Copyright © James Raynard 2023
std::chrono literals
• Repeat the previous exercise, using C++14 syntax
• 2 seconds
• 20 milliseconds
• 50 microseconds
Copyright © James Raynard 2023
Automatic Type Deduction
• Briefly describe the auto keyword
• Write down an expression which uses the auto keyword to define a
variable whose initial value is 6. What will be the type of this
variable?
Copyright © James Raynard 2023
Automatic Type Deduction
• Write down an expression which uses the auto keyword to define a
variable whose initial value is an iterator to the first element in a
vector of string
• Write down an expression which defines the same variable, using
traditional syntax for the type
Copyright © James Raynard 2023
auto with qualifiers
• What happens when we want to use auto to create a variable which is
const, or is a reference?
Copyright © James Raynard 2023
auto and for loops
• Write a program that creates a vector whose elements are 4, 2, 5, 3
and 1
• Using iterators with traditional syntax, write a loop that adds 2 to
each element
• Using iterators with traditional syntax, write a loop that prints out
each element
• Rewrite your program so that it uses auto for the iterator type instead
of an explicit type
Copyright © James Raynard 2023
Range for loops
• Rewrite your program from the previous exercise to use range-for
loops
Copyright © James Raynard 2023