C++ Exercises
Fill in the blanks to check your knowledge. Each exercise belongs to a lesson.
C++ Introduction
Exercise
Which object prints to the screen?
std:: << "Hi";
Syntax and Output
Exercise
Which operator sends values to cout?
cout "Hi";
C++ Get Started
Exercise
Choose the standard.
g++ -std= hello.cpp
C++ Comments
Exercise
One line comment.
noteVariables and Types
Exercise
Let the compiler pick the type.
x = 5;User Input
Exercise
Read a value into x.
cin x;
Operators
Exercise
Which operator gives the remainder?
17 5
Strings
Exercise
Get the number of characters.
s.()
Math Functions
Exercise
Raise 2 to the power 10.
(2, 10)C++ Data Types
Exercise
Deduce the type.
x = 5;Constants and Casts
Exercise
Safe conversion.
<double>(a)Enums and Structs
Exercise
Scoped enum.
enum Color { Red };
C++ String Methods
Exercise
Text to int.
("12")Input and Output Streams
Exercise
Two decimals.
cout << fixed << (2) << x;
Math and Random Numbers
Exercise
Power function.
(2, 10)Variables and Types
Exercise
Infer the type.
x = 10;cout and cin
Exercise
Print.
std:: << "hi";
std::string
Exercise
Length.
s.()
Reading Lines
Exercise
Read a line.
std::(in, s)
const and constexpr
Exercise
Compile time constant.
int N = 5;Casting
Exercise
Safe cast.
<int>(d)References
Exercise
Reference symbol.
int r = x;
Pointers
Exercise
Empty pointer.
int *p = ;
Namespaces
Exercise
Scope operator.
mathadd(1, 2)
Operators
Exercise
Remainder.
7 2
If and Switch
Exercise
Run when the condition is false.
if (ok) {} {}
Loops
Exercise
Walk through each item.
for (auto n names) {}
switch, Ternary and Range For
Exercise
Loop over a container.
for (int x v)
while, do while and break
Exercise
Run at least once.
{ } while (x);Structured Bindings and if init
Exercise
Unpack a pair.
auto [a, b] p;
if, else if and else
Exercise
Else branch.
if (x) {} {}
switch
Exercise
Stop fall through.
case 1: f(); ;
Loops
Exercise
Range for.
for (int v a)
Range based for
Exercise
No copy read only.
for ( auto &x : v)
break and continue
Exercise
Skip a round.
;Structured Bindings
Exercise
Unpack.
auto [a, ] = p;
Functions
Exercise
Pass by reference.
void addOne(int n)
Lambdas and Recursion
Exercise
Start a lambda with its capture list.
auto f = () { return 1; };
Reference and Default Parameters
Exercise
Pass by reference.
void f(int x)
Function Templates
Exercise
Template keyword.
<typename T>inline, constexpr and noexcept Functions
Exercise
Compile time function.
int f(int n)std::function and Callbacks
Exercise
Store a callable.
std::<int(int)> f
Functions
Exercise
Return type for nothing.
f() {}Default Arguments
Exercise
Default value.
int p(int a, int b 2)
Function Overloading
Exercise
Same name different types.
Overloads differ by Pass by Value, Reference and const Reference
Exercise
Read only no copy.
void f( std::string &s)
Lambdas
Exercise
Capture list.
[](int x) {}
std::function
Exercise
Callable wrapper.
std::<int(int)>
Function Templates
Exercise
Template keyword.
<typename T>Recursion
Exercise
Base case.
if (n <= 1) return ;
Arrays and Vectors
Exercise
Add an item to the end.
nums.(7);
Maps and Sets
Exercise
Test whether a key exists.
stock.("apple")
Pointers and References
Exercise
Read the value a pointer points to.
int v = p;
Dynamic Memory and Smart Pointers
Exercise
Create a uniquely owned object.
auto p = <Box>(7);
Vector In Depth
Exercise
Checked element access.
v.(3)
array, deque and list
Exercise
Fixed size container.
std::<int, 3> a
map, unordered_map and multimap
Exercise
Is the key present?
m.("a")
set, stack, queue and priority_queue
Exercise
Last in first out.
std::<int> st;
pair, tuple, optional and variant
Exercise
Empty optional.
return ;
string_view and Iterators
Exercise
Read only text view.
std:: sv = "x";
std::array and C Arrays
Exercise
Fixed size container.
std::<int, 3>
std::vector
Exercise
Add to the end.
v.(5)
2D Vectors
Exercise
Rows count.
g.()
std::map
Exercise
Sorted pairs.
std::<std::string, int>
unordered_map and unordered_set
Exercise
Hash container.
std::unordered<int>
std::set
Exercise
Unique sorted.
std::<int>
stack and queue
Exercise
LIFO container.
std::<int>
pair and tuple
Exercise
First of a pair.
p.Algorithms
Exercise
Sort.
std::(v.begin(), v.end())
Custom Sorting
Exercise
Comparator.
sort(b, e, )
Iterators
Exercise
Dereference.
*optional and variant
Exercise
Default value.
o.(7)
Classes and Objects
Exercise
Make a member visible outside the class.
class A { : int x; };
Inheritance and Polymorphism
Exercise
Allow a function to be overridden.
double area() const;Operator Overloading and Templates
Exercise
Declare a generic function.
<typename T> T id(T x) { return x; }Constructors, Destructors and RAII
Exercise
Destructor prefix.
Logger() {}Access Control, const and friend
Exercise
Method that does not modify the object.
int get() { return x; }
static Members and this
Exercise
Pointer to the current object.
return *;
Copy and Move Semantics
Exercise
Turn into an rvalue.
auto c = (a);
Virtual Functions and Abstract Classes
Exercise
Pure virtual marker.
virtual void f() 0;
Multiple Inheritance and Interfaces
Exercise
Inherit from two classes.
struct Duck : A B {}
Classes
Exercise
Private section.
:Constructors and Destructors
Exercise
Destructor prefix.
Res() {}Inheritance
Exercise
Derived from.
class Dog : Animal
Abstract Classes
Exercise
Pure virtual.
virtual double area() 0;
Operator Overloading
Exercise
Overload keyword.
V +(V a, V b)
static Members
Exercise
Shared member.
int n;struct
Exercise
Default access of struct.
struct is by default
enum class
Exercise
Scoped enum.
enum Color {}
Smart Pointers
Exercise
Single owner.
std::<int>
Move Semantics
Exercise
Move.
std::(a)
Algorithms and Iterators
Exercise
Sort a range.
(v.begin(), v.end());Exceptions
Exercise
Raise an error.
runtime_error("oops");Files
Exercise
Which class reads from a file?
in("a.txt");More STL Algorithms
Exercise
Sort a range.
(v.begin(), v.end())File Streams
Exercise
Read a file.
std:: in("a.txt");
chrono and filesystem
Exercise
Namespace for paths.
namespace fs = std::;
Regular Expressions and Text
Exercise
Replace matches.
(text, re, "x")Exceptions
Exercise
Catch block.
(const std::exception &e)File Streams
Exercise
Output file stream.
std:: out("f")
stringstream
Exercise
Build text.
std:: ss;
chrono and random
Exercise
Random engine.
std:: rng(42);
string_view
Exercise
Non owning view.
std:: sv
Practice: Word Frequency
Exercise
Increment.
freq[w]Practice: Palindrome
Exercise
Reverse iterator.
s.()
Practice: Top Scores
Exercise
Sort descending.
sort(v.(), v.rend())
Smart Pointers
Premium exercise. See plans
Class Templates
Premium exercise. See plans
Concepts and Constraints (C++20)
Premium exercise. See plans
Lambdas In Depth
Premium exercise. See plans
Rvalue References and Perfect Forwarding
Premium exercise. See plans
Threads, Mutexes and Atomics
Premium exercise. See plans
async, future and promise
Premium exercise. See plans
Exceptions and Exception Safety
Premium exercise. See plans
CMake and Build Systems
Premium exercise. See plans
Testing with GoogleTest and Catch2
Premium exercise. See plans
Debugging and Sanitizers
Premium exercise. See plans
Performance and Optimisation
Premium exercise. See plans
Libraries, Modules and Packages
Premium exercise. See plans
Where C++ Is Used
Premium exercise. See plans
C++ Best Practices
Premium exercise. See plans
Practice Projects
Exercise
Author of A Tour of C++.
Bjarne