0% found this document useful (0 votes)
94 views38 pages

C++, Python Cheat Sheet

The document provides a collection of programming idioms and their implementations in C++ and Python. It covers various common tasks such as printing strings, creating data structures, iterating over collections, and performing mathematical operations. Each idiom includes alternative implementations to illustrate different approaches in both programming languages.

Uploaded by

submitmyanswers
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
94 views38 pages

C++, Python Cheat Sheet

The document provides a collection of programming idioms and their implementations in C++ and Python. It covers various common tasks such as printing strings, creating data structures, iterating over collections, and performing mathematical operations. Each idiom includes alternative implementations to illustrate different approaches in both programming languages.

Uploaded by

submitmyanswers
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

The snippets are under the CC-BY-SA license.

[Link] Creative Commons Attribution-ShareAlike 3.0

Print Hello World


Print a literal string on std::cout << "Hello World" << std:: print("Hello World")
standard output endl;
Alternative implementation:

print('Hello World')

Print Hello 10 times


Loop to execute some for (int i = 0; i < 10; ++i) for _ in range(10):
code a constant cout << "Hello\n"; print("Hello")
number of times
Alternative implementation:

print("Hello\n"*10)

Alternative implementation:

i = 0
while i < 10:
print('Hello')
i += 1

Create a procedure
Like a function which
void finish(char* name){ def finish(name):
doesn't return any value,
cout << "My job here is done. G print(f'My job here is done. Go
thus has only side
oodbye " << name << "\n"; odbye {name}')
effects (e.g. Print to }
standard output)
Create a function
Create a function which
int square(int x){ def square(x):
returns the square of an return x*x; return x*x
integer
}
Alternative implementation:

def square(x):
return x**2

Create a 2D Point data


structure struct Point{ @dataclass
Declare a container type double x; class Point:
for two floating-point double y; x: float
numbers x and y }; y: float

Alternative implementation:

Point = namedtuple("Point", "x y")

Iterate over list values


Do something with each for(const auto &x : items) { for x in items:
item x of the list (or doSomething(x); doSomething( x )
array) items, regardless }
indexes. Alternative implementation:

[do_something(x) for x in items]


Iterate over list indexes
and values std::size_t i = 0; for i, x in enumerate(items):
Print each index i with for(const auto & x: items) { print(i, x)
its value x from an std::cout << "Item " << i++ << "
array-like collection = " << x << std::endl;
items }

Alternative implementation:

for (std::size_t ix = 0; ix < item


[Link](); ++ix) {
std::cout << "Item " << ix << " =
" << items[ix] << std::endl;
}

Create a map
(associative array) std::map<const char*, int> x; x = {"one" : 1, "two" : 2}
Create a new map x["one"] = 1;
object x, and provide
x["two"] = 2;
some (key, value) pairs
as initial content. Alternative implementation:

std::unordered_map<std::string, dou
ble> mymap = {
{"mom", 5.4},
{"dad", 6.1},
{"bro", 5.9}
};

Create a Binary Tree


data structure struct binary_tree class Node:
The structure must be { def __init__(self, data):
recursive because left int data; [Link] = data
child and right child are binary_tree *left = nullptr, *righ [Link] = None
binary trees too. A node t = nullptr; [Link] = None
has access to children };
nodes, but not to its Alternative implementation:
parent.
class Node:
def __init__(self, data, left_chi
ld, right_child):
[Link] = data
self._left_child = left_child
self._right_child = right_child

Shuffle a list
Generate a random
std::random_shuffle([Link](), [Link] shuffle(x)
permutation of the d());
elements of list x Alternative implementation:

[Link](x)
Pick a random element
from a list std::mt19937 gen; [Link](x)
The list x must be non- std::uniform_int_distribution<size_
empty. t> uid (0, [Link] () - 1);
x[uid (gen)];

Alternative implementation:

std::ranges::sample(x, &result, 1,
std::mt19937{std::random_device{}
()});

Check if list contains a


value bool Contains(const std::vector<int x in list
Check if the list > &list, int x)
contains the value x. {
list is an iterable finite
return std::find([Link]
container. (), [Link](), x) != [Link]();
}

Alternative implementation:

auto contains(auto list, auto x) ->


bool {
return std::ranges::find(list, x)
!= std::ranges::end(list);
}

Iterate over map keys


and values for (const auto& kx: mymap) { for k, v in [Link]():
Access each key k with std::cout << "Key: " << kx. print(k, v)
its value x from an first << " Value: " << [Link] <<
associative array std::endl;
mymap, and print them. }

Alternative implementation:

for (const auto& [k, x]: mymap) {


std::cout << "Key: " << k <
< " Value: " << x << '\n';
}

Alternative implementation:

for (auto entry : mymap) {


auto k = [Link];
auto x = [Link];
std::cout << k << ": " << x <<
"\n";
}

Pick uniformly a
random floating point
float pick(float a, float b) [Link](a,b)
number in [a..b)
{
Pick a random number
std::default_random_engine
greater than or equals
generator;
to a, strictly inferior to b.
std::uniform_real_distribut
Precondition : a < b.
ion distribution(a, b);
return distribution(generat
or);
}
Pick uniformly a
random integer in [a..b] std::mt19937 gen; [Link](a,b)
Pick a random integer std::uniform_int_distribution<size_
greater than or equals t> uid (a, b);
to a, inferior or equals to uid (gen);
b. Precondition : a < b.
Create a Tree data
structure template<typename T> class Node:
The structure must be struct Node{ def __init__(self, value, *chil
recursive. A node may T value; dren):
have zero or more std::vector<Node<T>> children; [Link] = value
children. A node has }; [Link] = list(childr
access to its children en)
nodes, but not to its
parent.
Depth-first traversal of
a tree void dfs(const auto &tree, const au def DFS(f, root):
Call a function f on to &root) f(root)
every node of a tree, in { for child in root:
depth-first prefix order f(root); DFS(f, child)

for (auto child : tree)


dfs(tree, child);
}

Reverse a list
Reverse the order of the
std::reverse(begin(x), end(x)); x = reversed(x)
elements of the list x.
This may reverse "in- Alternative implementation:
place" and destroy the
y = x[::-1]
original ordering.

Alternative implementation:

[Link]()
Return two values
Implement a function template<typename T, size_t len_x, def search(m, x):
search which looks for size_t len_y> for idx, item in enumerate(m):
item x in a 2D matrix m. std::pair<size_t, size_t> search (c if x in item:
Return indices i, j of the onst T (&m)[len_x][len_y], const T return idx, [Link]
matching cell. &x) { (x)
Think of the most for(size_t pos_x = 0; pos_x < l
idiomatic way in the en_x; ++pos_x) {
language to return the for(size_t pos_y = 0; pos_y
two values at the same < len_y; ++pos_y) {
time. if(m[pos_x][pos_y] ==
x) {
return std::pair<si
ze_t, size_t>(pos_x, pos_y);
}
}
}

// return an invalid value if n


1
5
2
6
4
3 ot found C++ Python
return std::pair<size_t, size_t
>(len_x, len_y);
}

Alternative implementation:

bool _search(const Matrix& _m, cons


9
7
10
8 t float _x, size_t* const out_i, si
ze_t* const out_j) {
for (size_t j = 0; j < _m.rows; j
++) {
for (size_t i = 0; i < _m.cols;
i++) {
if (_m.at(i, j) == _x) {
*out_i = i;
*out_j = j;
return true;
}
}
13
11
}
14
12
return false;
}
18
17
15
19
Swap values
Swap the values of the
swap(a, b); a, b = b, a
variables a and b
Alternative implementation:

a =int(input("enter a number"))
b =int(input("enter b number"))
a, b = b, a

print("Value of a:", a)
print("Value of a", b)
Convert string to
integer int i = std::atoi(s); i = int(s)
Extract the integer value
i from its string Alternative implementation:
representation s (in
int i = std::stoi(s);
radix 10)
20
21
Alternative implementation:

std::stringstream ss(str);
int i;
ss >> i;

Alternative implementation:

22 std::string s("123");
int i;
std::from_chars([Link](),
C++ [Link]() Python
+ [Link](), i, 10);

23 Convert real number to


string with 2 decimal
std::stringstream ss; s = '{:.2f}'.format(x)
places ss << std::fixed << std::setprecisi
Given a real number x,
on(2) << x;
Alternative implementation:
create its string s = [Link]();
s = f'{x:.2f}'
representation s with 2
decimal digits following
the dot.
24 Assign to string the
japanese word ネコ std::string s = u8" ネコ"; s = " ネコ"
Declare a new string s
and initialize it with the
ネコ
literal value " "
(which means "cat" in
japanese)
25 Send a value to another
thread
//declaration q = Queue()
Share the string value auto mutex = std::mutex{};
"Alan" with an existing
auto cv = std::condition_variable def worker():
running process which {}; while True:
will then display "Hello,
auto variable = std::optional<std:: print(f"Hello, {[Link]()}")
Alan" string>{}; q.task_done()
auto future = std::async([&]() {
auto lock = std::unique_loc Thread(target=worker, daemon=True).
k{mutex, std::defer_lock}; start()
[Link](lock, [&variable]()
{ return variable.has_value(); }); [Link]("Alan")
std::cout << "Hello, " << * [Link]()
variable << "!" << std::endl;
});

//passing value in main thread (or


it can be done in others as well)
{
auto lock = std::unique_loc
k{mutex};
variable = "Alan";
cv.notify_all();
}
26 Create a 2-dimensional
array std::vector<std::vector<double>> x x = [[0] * n for _ in range(m)]
Declare and initialize a (m, std::vector<double>(n));
matrix x having m rows
and n columns,
containing real
numbers.
27 Create a 3-dimensional
array std::vector<std::vector<std::vector x = [[[0 for k in range(p)] for j i
Declare and initialize a <double>>> x (m, std::vector<std::v n range(n)] for i in range(m)]
3D array x, having ector<double>> (n, std::vector<doub
dimensions boundaries le> (p)));
Alternative implementation:
m, n, p, and containing
x = [Link]((m,n,p))
real numbers.
28 Sort by a property
Sort the elements of the
std::sort(begin(items), end(items), items = sorted(items, key=lambda x:
list (or array-like [](const auto& a, const C++ auto& b) { x.p) Python
collection) items in
return a.p < b.p; });
ascending order of x.p, Alternative implementation:
where p is a field of the Alternative implementation:
items = sorted(items, key=attrgette
type Item of the objects
struct { r('p'))
in items.
bool operator()(const Item &lh
s, const Item &rhs) const { return
lhs.p < rhs.p; }
} custom_sort;

std::sort(begin(items), end(items),
custom_sort);

29 Remove item from list,


by its index [Link] ([Link] () + i); del items[i]
Remove i-th item from
list items. Alternative implementation:
This will alter the
[Link](i)
original list or return a
new list, depending on
which is more
idiomatic.
Note that in most
languages, the smallest
valid value for i is 0.
30 Parallelize execution of
1000 independent auto futures = std::vector<std::fut pool = Pool()
tasks ure<void>>{}; for i in range(1, 1001):
Launch the concurrent for (auto i = 1; i <= 1000; ++i) pool.apply_async(f, [i])
execution of procedure {
f with parameter i from futures.emplace_back(std::a
1 to 1000. sync(f, i));
Tasks are independent }
and f(i) doesn't return
any value.
Tasks need not run all
at the same time, so
you may use a pool.
31 Recursive factorial
(simple) unsigned int f( unsigned int i ) { def f(i):
Create the recursive if ( i == 0 ) return 1; if i == 0:
function f which returns return 1
the factorial of the non- return i * f( i - 1 ); else:
negative integer i, } return i * f(i-1)
calculated from f(i-1)
32 Integer exponentiation
by squaring int pow(int x, int p) def exp(x, n):
Create function exp { return x**n
which calculates (fast) if (p == 0) return 1;
the value x power n. if (p == 1) return x;
x and n are non-
negative integers. int tmp = pow(x, p/2);
if (p%2 == 0) return tmp * tmp;
else return x * tmp * tmp;
}
C++ Python
33 Atomically read and
update variable std::atomic<int> x{}; lock = [Link]()
Assign to the variable x
the new value f(x), auto local_x = [Link](); [Link]()
making sure that no
while(!x.compare_exchange_strong(lo try:
other thread may cal_x, f(local_x))) { x = f(x)
modify x between the local_x = [Link](); finally:
read and the write. } [Link]()

Alternative implementation: Alternative implementation:

//declaration with [Link]():


auto mutex = std::mutex{}; x = f(x)
auto x = someValue();

//use
{
auto lock = std::unique_loc
k{mutex};
x = f(x);
}

34 Create a set of objects


Declare and initialize a std::unordered_set<T> x; class T(object):
set x containing unique pass
objects of type T. Alternative implementation:
x = set(T())
std::unordered_set<T, hasher, eq>
x;
Alternative implementation:

class T:
...

s = set(T() for _ in range(x))


35 First-class function :
compose std::function<C (A)> compose(B (&f) def compose(f, g):
Implement a function (A), C (&g)(B)) return lambda a: g(f(a))
compose (A -> C) with {
parameters f (A -> B) return [&f, &g](A a){return g(f
and g (B -> C), which (a));};
returns the composition }
function g ∘ f
auto fn = compose(f, g);

36 First-class function :
generic composition
template<typename Pred1, typename P def compose(f, g):
Implement a function red2> return lambda x: g(f(x))
compose which returns auto compose(Pred1 f, Pred2 g){
composition function g return [f,g](auto x){ return g(f
∘ f for any functions f (x)); };
and g having exactly 1 }
parameter. C++ Python
37 Currying
Transform a function // function taking many parameters def add(a, b):
that takes multiple
int add(int a, int b) return a+b
arguments into a {
function for which some
return a + b; add_to_two = partial(add, 2)
of the arguments are }
preset.
// define a new function preseting
the first parameter
std::function<int (int)> add_def(in
t a)
{
return [a](int b){return add(a,
b);};
}

int result = add_def(4)(6);

Alternative implementation:

//function
auto add(int a, int b) -> int {
return a + b;
}

//curry with std::bind


using namespace std::placeholders;
auto add5 = std::bind(add, _1, 5);

//curry with lambda


auto add5 = [](int x) { return add
(x, 5); };

//use
auto result = add5(1);
assert(result == 6);
38 Extract a substring
Find substring t auto t = [Link](i, j-i); t = s[i:j]
consisting in characters
i (included) to j
(excluded) of string s.
Character indices start
at 0 unless specified
otherwise.
Make sure that
multibyte characters are
properly handled.
39 Check if string contains
a word bool ok = [Link](word) != std::stri ok = word in s
Set the boolean ok to ng::npos;
true if the string word is
contained in string s as
a substring, or to false
C++ Python
otherwise.
41 Reverse a string
Create string t std::string s("Example"); t = [Link]('utf8')[::-1].encode
containing the same std::string t; ('utf8')
characters as string s, std::copy([Link](), [Link](), s
in reverse order. td::back_inserter(t));
Alternative implementation:
Original string s must
t = s[::-1]
remain unaltered. Each
character must be
handled correctly
regardless its number
of bytes in memory.
42 Continue outer loop
Print each item v of list auto a = {1,2,3,4,5}; for v in a:
a which is not contained auto b = {3,5}; try:
in list b. for u in b:
For this, write an outer for (auto va: a){ if v == u:
loop to iterate on a and for (auto vb: b){ raise Exception()
an inner loop to iterate if (va==vb) goto OUTER; print(v)
on b. } except Exception:
std::cout << va << '\n'; continue
OUTER: continue;
} Alternative implementation:

for v in a:
keep = True
for w in b:
if w == v:
keep = False
break
if keep:
print(v)
43 Break outer loop
Look for a negative auto indices = findNegativeValue class BreakOuterLoop (Exception): p
value v in 2D integer (m, 10, 20); ass
matrix m. Print it and std::cout << m[[Link]][indic
stop searching. [Link]] << '\n'; try:
position = None
std::pair<int, int> findNegativeVal for row in m:
ue (int **m, int rows, int columns) for column in m[row]:
{ if m[row][column] == v:
for (int i = 0; i < rows; ++i) { position = (row, co
for (int j = 0; j < columns; ++ lumn)
j) { raise BreakOuterLoo
if (m[i][j] < 0) return make_ p
pair (i, j); except BreakOuterLoop:
} pass
}
throw "No negative value!";
Alternative implementation:
} C++ Python
def loop_breaking(m, v):
for i, row in enumerate(m):
for j, value in enumerate(r
ow):
if value == v:
return (i, j)
return None

print(loop_breaking(([1,2,3],[4,5,
6],[7,8,9]), 6))

Alternative implementation:

matrix = [[1,2,3],[4,-5,6],[7,8,9]]
try:
print(next(i for i in [Link]
m_iterable(matrix) if i < 0))
except StopIteration:
pass

44 Insert element in list


Insert the element x at
[Link] ([Link] () + i, x); [Link](i, x)
position i in the list s.
Further elements must
be shifted to the right.
45 Pause execution for 5
seconds
std::this_thread::sleep_for(5s); [Link](5)
Sleep for 5 seconds in
current thread, before
proceeding with the
next instructions.
46 Extract beginning of
string (prefix)
auto t = [Link](0, 5); t = s[:5]
Create the string t
consisting of the 5 first
characters of the string
s.
Make sure that
multibyte characters are
properly handled.
47 Extract string suffix
Create string t std::string t = [Link]([Link]() t = s[-5:]
consisting in the 5 last - 5);
characters of string s.
Make sure that
multibyte characters are
properly handled.
48 Multi-line string literal
Assign to variable s a std::string s = R"( Earth is a plan s = """Huey
string literal consisting et. Dewey
in several lines of text, So is the Jupiter)"; Louie"""
including newlines.
49 Split a space-separated
string std::istringstream x(s); chunks = [Link]()
Build list chunks std::list<std::string> chunks;
consisting in substrings std::copy(std::istream_iterator<st
of the string s, d::string>(x), std::istream_iterato
C++ Python
separated by one or r<std::string>(), std::back_inserte
more space characters. r(chunks));

50 Make an infinite loop


Write a loop that has no
for (;;) { while True:
end clause.
/// Do something pass
}

Alternative implementation:

while (true) {
// Do something
}

51 Check if map contains


key bool key_exists = [Link](k) != [Link] k in m
Determine whether the d();
map m contains an
entry for the key k Alternative implementation:

bool key_exists = [Link](k) != 0;

Alternative implementation:

bool key_exists = [Link](k);

52 Check if map contains


value std::find_if([Link](), [Link](), v in [Link]()
Determine whether the
[v](const auto& mo) {return [Link]
map m contains an
nd == v; }) != [Link]();
entry with the value v,
for some key.
53 Join a list of strings
Concatenate elements std::vector<std::string> x; y = ', '.join(x)
of string list x joined by std::string y;
the separator ", " to const char* const delim = ", "; Alternative implementation:
create a single string y.
switch ([Link]()) y = ', '.join(map(str, x))
{
case 0: y = ""; break;
case 1: y = x[0]; break;
default:
std::ostringstream
os;
std::copy([Link]
(), [Link]() - 1,
std::ostrea
m_iterator<std::string>(os, deli
m));
os C++
<< *[Link](); Python
y = [Link]();
}

Alternative implementation:

y = x | views::join_with(',') | to<
std::string>();

54 Compute sum of
integers int s = std::accumulate([Link](), s = sum(x)
Calculate the sum s of
[Link](), 0, std::plus<int>());
the integer list or array
x.
55 Convert integer to
string
auto s = std::to_string(i); s = str(i)
Create the string
representation s (in
radix 10) of the integer
value i.
57 Filter list
Create the list y std::copy_if ([Link] (), [Link] (), y = list(filter(p, x))
containing the items
std::back_inserter(y), p);
from the list x that Alternative implementation:
satisfy the predicate p.
y = [element for element in x if p
Respect the original
(element)]
ordering. Don't modify x
in-place.
58 Extract file content to a
string std::string fromFile(std::string _ lines = open(f).read()
Create the string lines
f)
from the content of the
{
Alternative implementation:
file with filename f. std::ifstream t(_f);
[Link](0, std::ios::end); with open(f) as fo:
size_t size = [Link](); lines = [Link]()
std::string buffer(size, ' ');
[Link](0);
[Link](&buffer[0], size);
}
59 Write to standard error
stream std::cerr << x << " is negative\n"; print(x, "is negative", file=[Link]
Print the message "x is derr)
negative" to standard Alternative implementation:
error (stderr), with
int main(){
integer x value
int x = -2;
substitution (e.g. "-2 is
std::cerr << x <<" is negat
negative").
ive\n";
}

60 Read command line


argument int main(int argc, char *argv[]) x = [Link][1]
Assign to x the string
{
value of the first
vector<string> args(1 + argv, argc
command line + argv);
parameter, after the
program name.
string x = [Link](0);
C++ Python
}

61 Get current date


Assign to the variable d std::time_t d = std::time(nullptr); d = [Link]()
the current date/time
value, in the most
standard type.
62 Find substring position
Set i to the first position int i = [Link](y); i = [Link](y)
of string y inside string
x, if exists.

Specify if i should be
regarded as a character
index or as a byte index.

Explain the behavior


when y is not contained
in x.
63 Replace fragment of a
string std::stringstream s; x2 = [Link](y, z)
Assign to x2 the value std::regex_replace(std::ostreambuf_
of string x with all iterator<char>(s), [Link](), [Link]
occurrences of y (), y, z);
replaced by z. auto x2 = [Link]()
Assume occurrences of
y are not overlapping.
68 Create a bitset
Create an object x to std::vector<bool> x(n, 0); x = bytearray(int([Link](n / 8.
store n bits (n being 0)))
potentially large). Alternative implementation:

std::bitset<n> x;
69 Seed random generator
Use seed s to initialize a srand(s); rand = [Link](s)
random generator.

If s is constant, the
generator output will be
the same each time the
program runs. If s is
based on the current
value of the system
clock, the generator
output will be different
each time.
71 Echo program
implementation int main(int argc, char * argv[]) print(' '.join([Link][1:]))
Basic implementation {
of the Echo program: for(int i = 1; i < argc; ++
i) C++ Python
Print all arguments
except the program {
name, separated by std::cout <<(1==i ?
space, followed by "" : " ") << argv[i];
newline. }
The idiom std::cout <<std::endl;
demonstrates how to }
skip the first argument
if necessary,
concatenate arguments
as strings, append
newline and print it to
stdout.
73 Create a factory
Create a factory named template <typename T, def fact(a_class, str_):
fact for any sub class of std::enable_if_t< if issubclass(a_class, Parent):
Parent and taking std::is_base_of_v<Paren return a_class(str_)
exactly one string str as t, T>, bool> = true>
constructor parameter. T fact(const std::string& str) {
return T(str);
}

74 Compute GCD
Compute the greatest
unsigned long long int GCD(unsigned x = gcd(a, b)
common divisor x of big
long long int a, unsigned long long
integers a and b. Use an int b) Alternative implementation:
integer type able to
{
unsigned long long int c=a%b; x = [Link](a, b)
handle huge numbers.
if(c==0)
return b;
return GCD(b, c);
}

Alternative implementation:

auto x = std::gcd(a, b);

75 Compute LCM
Compute the least auto x = std::lcm(a, b); x = (a*b)//gcd(a, b)
common multiple x of
big integers a and b. Alternative implementation:
Use an integer type able
x = [Link](a, b)
to handle huge
numbers.
76 Binary digits from an
integer std::bitset<sizeof(x)*8> y(x); s = '{:b}'.format(x)
Create the string s of auto s = y.to_string();
integer x written in base
2.

E.g. 13 -> "1101"


77 Complex number
Declare a complex x using namespace std::complex_litera x = 3j-2
and initialize it with ls; y = x * 1j
value (3i - 2). Then
multiply it by i. auto x = 3i - 2.;
x *= 1i;

78 "do while" loop


Execute a block once,
do { while True:
then execute it again as someThing(); do_something()
long as boolean
someOtherThing();C++ if not c: Python
condition c is true.
} while(c); break

79 Convert integer to
floating point number float y = static_cast<float>(x); y = float(x)
Declare the floating
point number y and
initialize it with the
value of the integer x .
80 Truncate floating point
number to integer int y = static_cast<int>(x); y = int(x)
Declare integer y and
initialize it with the
value of floating point
number x . Ignore non-
integer digits of x .
Make sure to truncate
towards zero: a
negative x must yield
the closest greater
integer (not lesser).
81 Round floating point
number to integer int y = static_cast<int>(std::floor y = int(x + 0.5)
Declare the integer y (x + 0.5f));
and initialize it with the
rounded value of the
floating point number x .
Ties (when the
fractional part of x is
exactly .5) must be
rounded up (to positive
infinity).
83 Regex with character
repetition auto r = regex("htt+p"); r = [Link](r"htt+p")
Declare regular
expression r matching
strings "http", "htttp",
"httttp", etc.
84 Count bits set in integer
binary representation uint32_t c = 0; c = bin(i).count("1")
Count number c of 1s in for (; i; i &= i - 1, ++c);
the integer i in base 2. Alternative implementation:

c = i.bit_count()
E.g. i=6 → c=2
85 Check if integer
addition will overflow
bool addingWillOverflow(int x, int def adding_will_overflow(x,y):
Write boolean function y) { return False
addingWillOverflow
return ((x > 0) && (y > std::nume
which takes two
ric_limits<int>::max() - x)) ||
integers x, y and return ((x < 0) && (y < std::nume
true if (x+y) overflows. ric_limits<int>::min() - x));
}
An overflow may be
above the max positive
value, or below the min C++ Python
negative value.
87 Stop program
Exit immediately. exit(1); [Link](1)
If some extra cleanup
work is executed by the
program runtime (not by
the OS itself), describe
it.
88 Allocate 1M bytes
Create a new bytes vector<byte> _buf(1'000'000); buf = bytearray(1000000)
buffer buf of size
1,000,000.
89 Handle invalid
argument throw domain_error("oops!"); raise ValueError("x is invalid")
You've detected that the
integer value of
argument x passed to
the current function is
invalid. Write the
idiomatic way to abort
the function execution
and signal the problem.
90 Read-only outside
Expose a read-only
class Foo final { class Foo(object):
integer x to the outside int mX = 0; def __init__(self):
world while being self._x = 0
writable inside a
public:
structure or a class Foo.
const auto& X() const { return m @property
X; } def x(self):
}; """
Doc for x
"""
return self._x

93 Pass a runnable
procedure as parameter void control(invocable auto&& f) def control(f):
Implement the { f()
procedure control which f();
receives one parameter }
f, and runs f.
94 Print the type of a
variable std::cout<<typeid(x).name(); print(type(x))
Print the name of the
type of x. Explain if it is Alternative implementation:
a static type or dynamic
print(x.__class__)
type.

This may not make


sense in all languages.
95 Get file size
Assign to variable x the std::ifstream f(path, std::ios::in x = [Link](path)
length (number of | std::ios::binary);
bytes) of the local file at [Link](0, std::ios::end);
path. size_t x = [Link]();

96 Check string prefix


Set the boolean b to bool b = s.starts_with(prefix); b = [Link](prefix)
true if string s starts C++ Python
with prefix prefix, false Alternative implementation:
otherwise.
std::string prefix = "something";
bool b = [Link](0, [Link]
(), prefix) == 0;

97 Check string suffix


Set boolean b to true if return [Link]() == [Link]() - b = [Link](suffix)
string s ends with string [Link](suffix);
suffix, false otherwise.
Alternative implementation:

bool b = s.ends_with(suffix);

98 Epoch seconds to date


object
std::time_t d = std::chrono::system d = [Link](ts)
Convert a timestamp ts _clock::to_time_t(ts);
(number of seconds in
epoch-time) to a date
with time d. E.g. 0 ->
1970-01-01 [Link]
99 Format date YYYY-MM-
DD
int main() d = date(2016, 9, 28)
Assign to the string x { x = [Link]('%Y-%m-%d')
the value of the fields
char x[32]{};
(year, month, day) of the
time_t a = time(nullptr); Alternative implementation:
date d, in format YYYY-
struct tm d;
if (localtime_s(&d, &a) == d = [Link]()
MM-DD.
0) { x = [Link]()
strftime(x, sizeof
(x), "%F", &d);
std::cout << x << s
td::endl;
}

return 0;

}
100 Sort by a comparator
Sort elements of array- struct is_less { [Link](key=c)
like collection items, bool operator () (int a, int b)
using a comparator c. { Alternative implementation:
return a < b;
} [Link](key=functools.cmp_to_key
}; (c))

int main(){
std::vector<int> items = {1337,
666, -666, 0, 0, 666, -666};
std::sort([Link](), items.
end(), is_less());

std::vector<int> expected = {-6


66, -666, 0, 0, 666, 666, 1337};
assert([Link]() == expecte
[Link]()); C++ Python
for (size_t i = 0; i < [Link]
ze(); i++){
assert(items[i] == expected
[i]);
}
return 0;
}

105 Current executable


name
s = [Link][0]
Assign to the string s int main(int argc, char* argv[])
the name of the
{
currently executing
std::cout << std::filesystem::p
program (but not its full
ath(argv[0]).filename() << '\n';
path). }

106 Get program working


directory dir = std::filesystem::current_path dir = [Link]()
Assign to string dir the ();
path of the working
directory.
(This is not necessarily
the folder containing
the executable itself)
109 Number of bytes of a
type std::size_t n = sizeof(t); n = [Link](t)
Set n to the number of
bytes of a variable t (of
type T).
110 Check if string is blank
Set the boolean blank to bool blank = false; blank = not s or [Link]()
true if the string s is if ([Link]() || std::all_of([Link]
empty, or null, or n(), [Link](), [](char c){return st
contains only d::isspace(c);})) {
whitespace ; false blank = true;
otherwise. }
112 Iterate over map
entries, ordered by keys std::map< K, V > _mymap; for k in sorted(mymap):
Print each key k with its for (const auto& pair : _mymap) { print(mymap[k])
value x from an std::cout << [Link] << ": "
associative array << [Link] << "\n";
mymap, in ascending }
order of k.
Alternative implementation:

auto print(auto&... args) {


// c++17 fold expression
(std::cout << ... << args) << st
d::endl;
}

auto print_map_contents(auto mymap)


{
// c++17 structured
C++ binding Python
for (auto [k, x] : mymap) {
print("mymap[", k, "] = ", x);
}
}

auto main() -> int {


// map is ordered map, iteration
is ascending by key value
auto map = std::map<std::string,
int> {
{"first entry", 12},
{"second entry", 42},
{"third entry", 3},
};

print_map_contents(map);
}

113 Iterate over map


entries, ordered by
for_each(begin(mymap), end(mymap), for x, k in sorted((x, k) for k,x i
values
[&s](const auto& kv) { [Link] n [Link]()):
Print each key k with its ([Link]); }); print(k, x)
value x from an
associative array Alternative implementation:
mymap, in ascending
for key, value in sorted([Link](),
order of x.
key=[Link](1)):
Multiple entries may
print(key, value)
exist for the same value
x.
117 Get list size
Set n to the number of
size_t n = [Link](); n = len(x)
elements of the list x.
118 List to set
Create the set y from std::unordered_set<T> y ([Link] y = set(x)
the list x.
(), [Link] ());
x may contain
duplicates. y is Alternative implementation:
unordered and has no
std::set<T> y ([Link] (), [Link]
repeated values.
());
119 Deduplicate list
Remove duplicates std::sort([Link](), [Link]()); x = list(set(x))
from the list x. auto last = std::unique([Link](),
Explain if the original [Link]()); Alternative implementation:
order is preserved. [Link](last, [Link]());
x = list(OrderedDict(zip(x, x)))
Alternative implementation:
Alternative implementation:
std::vector<std::string> x = {"on
e", "two", "two", "one", "three"}; def dedup(x):
std::unordered_set<std::string> t; y = []
for (auto e : x) for i in x:
[Link](e); if not i in y:
[Link](i)
return y

120 Read integer from stdin


Read an integer value std::cin >> n; n = int(input("Input Prompting Stri
C++ Python
from the standard input
ng: "))
into the variable n
122 Declare an enumeration
Create an enumerated enum class Suit { class Suit:
type Suit with 4 possible
SPADES, HEARTS, DIAMONDS, CLUBS SPADES, HEARTS, DIAMONDS, C
values SPADES,
}; LUBS = range(4)
HEARTS, DIAMONDS,
CLUBS. Alternative implementation: Alternative implementation:

enum class Color : char{ class Suit(Enum):


Red, Black, Green SPADES = 1
}; HEARTS = 2
DIAMONDS = 3
CLUBS = 4

123 Assert condition


Verify that predicate assert(isConsistent()); assert isConsistent
isConsistent returns
true, otherwise report
assertion violation.
Explain if the assertion
is executed even in
production environment
or not.
124 Binary search for a
value in sorted array template<typename T> def binarySearch(a, x):
Write the function int binarySearch(const std::vector< i = bisect.bisect_left(a, x)
binarySearch which T> &a, const T &x) return i if i != len(a) and a
returns the index of an { [i] == x else -1
element having the if([Link]() == 0) return -1;
value x in the sorted
array a, or -1 if no such size_t lower = 0;
element exists. size_t upper = [Link]() - 1;

while(lower <= upper)


{
auto mid = lower + (upper-l
ower) / 2;

if(x == a[mid])
{
return C++
(int)mid; Python
}
else if(x > a[mid])
{
lower = mid + 1;
}
else
{
upper = mid - 1;
}
}

return -1;
}

125 Measure function call


duration auto start = std::chrono::steady_cl t1 = time.perf_counter_ns()
measure the duration t, ock::now(); foo()
in nanoseconds, of a
foo(); t2 = time.perf_counter_ns()
call to the function foo. auto end = std::chrono::steady_cloc print('Nanoseconds:', t2 - t1)
Print this duration.
k::now();
auto t = std::chrono::duration_cast
<std::chrono::nanoseconds>(end-star
t).count();

126 Multiple return values


Write a function foo that std::tuple<std::string, bool> foo() def foo():
returns a string and a { return 'string', True
boolean value. return std::make_tuple("someStrin
g", true);
}

Alternative implementation:

auto foo()
{
return std::make_tuple("Hello",
true);
}

127 Source code inclusion


Import the source code
void _foo() { foo = imp.load_module('foobody', 'f
for the function foo #include "[Link]" [Link]').foo
body from a file }
"[Link]".
128 Breadth-first traversing
of a tree void bfs(Node& root, std::function< def BFS(f, root):
Call a function f on void(Node*)> f) { Q = [root]
every node of a tree, in std::deque<Node*> node_queue; while Q:
breadth-first prefix order node_queue.push_back(&root); n = [Link](0)
while (!node_queue.empty()) { f(n)
Node* const node = node_queue.f for child in n:
ront(); if not [Link]
node_queue.pop_front(); scovered:
f(node); n.d
for (Node* const child : node-> iscovered = True
children) { Q.a
node_queue.push_back(child); ppend(n)
}
}
}

130 Depth-first traversal in C++ Python


a graph
void dfs(Node& root, std::function< def depth_first(start, f):
Call th function f on void(Node*)> f) { seen = set()
every vertex accessible std::stack<Node*> queue; stack = [start]
from the vertex v, in
[Link](&root); while stack:
depth-first prefix order std::unordered_set<const Node*> v vertex = [Link]()
isited; f(vertex)
while (![Link]()) { [Link](vertex)
Node* const node = [Link](); [Link](
[Link](); v for v in [Link] if
f(node); v not in seen
[Link](node); )
for (Node* const neighbor : nod
e->neighbors) {
if ([Link](neighbor) ==
[Link]()) {
[Link](neighbor);
}
}
}
}
131 Successive conditions
Execute f1 if condition if (c1) f1() if c1 else f2() if c2 else f3
c1 is true, or else f2 if f1(); () if c3 else None
condition c2 is true, or else if (c2)
else f3 if condition c3 is f2(); Alternative implementation:
true. else if (c3)
f3(); if c1:
Don't evaluate a
f1()
condition when a
elif c2:
previous condition was Alternative implementation:
f2()
true.
if (c1) elif c3:
{ f3()
f1();
}
else if (c2)
{
f2();
} C++ Python
else if (c3)
{
f3();
}

Alternative implementation:

(c1 && (f1(), true))


|| (c2 && (f2(), true))
|| (c3 && (f3(), true));

132 Measure duration of


procedure execution std::clock_t start = std::clock(); duration = [Link]("f()", set
Run the procedure f, f(); up="from __main__ import f")
and return the duration
double duration = (std::clock() - s
of the execution of f. tart) / (double) CLOCKS_PER_SEC;
Alternative implementation:

start = [Link]()
Alternative implementation:
f()
#include <chrono> end = [Link]()
return end - start
double measure() {
using namespace std::chrono;
const auto start{ high_resoluti
on_clock::now() };
f();
const auto elapsed{ high_resolu
tion_clock::now() - start };
const double seconds{ duration_
cast<duration<double>>(elapsed).cou
nt() };
return seconds;
}

133 Case-insensitive string


contains auto ok = std::search(std::begin ok = [Link]() in [Link]()
Set boolean ok to true if (s), std::end(s), std::begin(word),
string word is contained std::end(word),
in string s as a [](auto c, auto d){
substring, even if the return std::tolower(c) == s
case doesn't match, or td::tolower(d);
to false otherwise. }
) != std::end(s);
134 Create a new list
Declare and initialize a std::vector<T> items = {a, b, c}; items = [a, b, c]
new list items,
containing 3 elements Alternative implementation:
a, b, c.
list items { a, b, c };

135 Remove item from list,


by its value erase(items, x); [Link](x)
Remove at most 1 item
from list items, having
the value x.
This will alter the
original list or return a
new list, depending on
which is more
idiomatic.
If there are several C++ Python
occurrences of x in
items, remove only one
of them. If x is absent,
keep items unchanged.
136 Remove all occurrences
of a value from a list [Link](x); newlist = [item for item in items i
Remove all occurrences f item != x]
of the value x from list
items.
This will alter the
original list or return a
new list, depending on
which is more
idiomatic.
137 Check if string contains
only digits bool b = false; b = [Link]()
Set the boolean b to
if (! [Link]() && std::all_of([Link]
true if the string s gin(), [Link](), [](char c){return s
contains only td::isdigit(c);})) {
characters in the range
b = true;
'0'..'9', false otherwise. }

140 Delete map entry


Delete from map m the [Link](k); [Link](k, None)
entry having key k.

Explain what happens if


k is not an existing key
in m.
141 Iterate in sequence
over two lists void print_seq(const auto& ...xs) for x in items1 + items2:
Iterate in sequence over { print(x)
the elements of the list (std::for_each(std::begin(xs), st
items1 then items2. For d::end(xs),
each iteration print the [](const auto& x) { st
element. d::cout << x; }), ...);
}

std::list xs { "hi", "there", "wor


ld" }, ys { "lo" "thar" };

print_seq(xs, ys);
142 Hexadecimal digits of
an integer template <typename I> s = hex(x)
Assign to string s the std::string n2hexstr(I w, size_t he
hexadecimal x_len = sizeof(I)<<1) {
representation (base static const char* digits = "01
16) of integer x. 23456789ABCDEF";
std::string str(hex_len, '-
E.g. 999 -> "3e7" ');
for (size_t i=0, j=(hex_len-1)*
4 ; i<hex_len; ++i,j-=4)
str[i] = digits[(w>>j) & 0x0
f];
return str;
}

Alternative implementation:

std::ostringstream C++
stream; Python
stream << std::hex << x;
s = [Link]();

144 Check if file exists


Set boolean b to true if bool b = std::filesystem::exists(f b = [Link](fp)
file at path fp exists on
p);
filesystem; false Alternative implementation:
otherwise.
b = Path(fp).exists()
Beware that you should
never do this and then
in the next instruction
assume the result is still
valid, this is a race
condition on any
multitasking OS.
146 Convert string to
floating point number float f = std::stof(s); s = u'545,2222'
Extract floating point [Link](locale.LC_ALL, 'd
value f from its string
e')
representation s f = [Link](s)

Alternative implementation:

f = float(s)

Alternative implementation:

f = float(s)

147 Remove all non-ASCII


characters copy_if(begin(src), end(src), back t = [Link]('[^\u0000-\u007f]', '',
Create string t from _inserter(dest), s)
string s, keeping only [](const auto c) { return
ASCII characters static_cast<unsigned char>(c) <= 0x
Alternative implementation:
7F; });
t = [Link]("ascii", "ignore").dec
ode()
148 Read list of integers
from stdin vector<int> v; list(map(int, input().split()))
Read a list of integer for(int t;;){
numbers from the cin >> t;
Alternative implementation:
standard input, until if([Link]())
break; numbers = [int(x) for x in input().
EOF.
v.push_back(t); split()]
}

150 Remove trailing slash


Remove the last
if('/' == [Link]()) p = [Link]("/")
character from the s.pop_back();
string p, if this character
is a forward slash /
152 Turn a character into a
string
string s { 'c' }; s = c
Create string s
containing only the C++ Python
character c.
153 Concatenate string with
integer auto t = s + std::to_string (i); t = f"{s}{i}"
Create the string t as
the concatenation of
the string s and the
integer i.
155 Delete file
Delete from filesystem
auto r = std::filesystem::remove(fi path = [Link](_filepath)
the file having path lepath); [Link]()
filepath.
Alternative implementation:

[Link](filepath)

157 Declare constant string


Initialize a constant // using char* PLANET = 'Earth'
planet with string value constexpr char planet[] = "Earth";
"Earth".
// using string
const std::string planet{"Earth"};

160 Detect if 32-bit or 64-


bit architecture #ifdef __x86_64 if [Link] > 2**32:
Execute f32() if f64(); f64()
platform is 32-bit, or #else else:
f64() if platform is 64-
#ifdef _M_AMD64 f32()
bit. f64();
This can be either a #else
compile-time condition
f32();
(depending on target) or #endif
a runtime detection. #endif

Alternative implementation:

if constexpr(sizeof(nullptr) == 8)
{
f64();
} else {
f32();
}
161 Multiply all the
elements of a list for (auto &it : elements) elements = [c * x for x in element
Multiply all the it *= c; s]
elements of the list
elements by a constant Alternative implementation:
c
std::transform(std::begin(element
s), std::end(elements), std::begin
(elements), [c](auto i){
return i*c;
});

165 Last element of list


Assign to the variable x std::vector<int> items; x = items[-1]
the last element of the int last = [Link]();
list items.
Alternative implementation:
C++ Python
auto x = *std::crbegin(items);

166 Concatenate two lists


Create the list ab auto ab = a; ab = a + b
containing all the [Link] ([Link] (), [Link] (),
elements of the list a, [Link] ());
followed by all the
elements of the list b.
169 String length
Assign to the integer n auto utf8len(std::string_view const n = len(s)
the number of & s) -> size_t
characters of the string {
s. std::setlocale(LC_ALL, "en_
Make sure that US.utf8");
multibyte characters are
properly handled. auto n = size_t{};
n can be different from auto size = size_t{};
the number of bytes of auto mb = std::mbstate_t{};
s.
while(size < [Link]())
{
size += mbrlen([Link]
ta() + size, [Link]() - size, &m
b);
n += 1;
}

return n;
}

170 Get map size


Set n to the number of auto n = [Link](); n = len(mymap)
elements stored in
mymap.

This is not always equal


to the map capacity.
171 Add an element at the
end of a list s.emplace_back(x); [Link](x)
Append the element x
to the list s. Alternative implementation:

s.push_back(x);
172 Insert an entry in a map
Insert value v for key k m[k] = v; m[k] = v
in map m.
179 Get center of a
rectangle template <typename T> struct Point center = ((x1+x2)/2, (y1+y2)/2)
Return the center c of {
the rectangle with T x = {};
Alternative implementation:
coördinates(x1,y1,x2,y2) T y = {};
}; Point = namedtuple('Point', 'x y')
template <typename T> struct Rectan center = Point((x1+x2)/2, (y1+y2)/
gle { 2)
Point<T> upper_left;
Point<T> lower_right;
};
template <typename T>
Point<T> get_center(const Rectangle
<T>& rect) {
return { C++ Python
.x = (rect.upper_left.x + rect.
lower_right.x) / 2,
.y = (rect.upper_left.y + rect.
lower_right.y) / 2,
};
}

180 List files in directory


Create the list x
auto directory_contents(auto path) x = [Link](d)
containing the contents {
of the directory d. auto iterator = std::filesystem::
directory_iterator(path);
x may contain files and return std::vector<std::filesyste
subfolders.
m::path>(
No recursive subfolder std::ranges::begin(iterator),
listing. std::ranges::end(iterator)
);
}

auto main(int argc, char** argv) ->


int {
auto path = argc >= 2
? std::filesystem::path(argv
[1])
: std::filesystem::current_path
();

for (auto entry : directory_conte


nts(path)) {
std::cout << [Link]() <<
std::endl;
}
}
189 Filter and transform list
Produce a new list y template <typename SeqT> y = [T(e) for e in x if P(e)]
containing the result of auto transform_copy_if(const SeqT
the function T applied i, auto p, auto f)
Alternative implementation:
to all elements e of the {
using namespace std; y = list(map(T, filter(P, x)))
list x that match the
predicate P.
SeqT o;

for_each(begin(i), end(i),
[&](const auto& x) {
if(p(x))
o.push_back(f(x));
}
);

return o;
} C++ Python

Alternative implementation:

constexpr auto transform_matches(co


nst auto& x, auto p, auto t) {
auto result = x
| std::views::filter(p)
| std::views::transform(t);

std::vector<std::ranges::range_
value_t<decltype(result)>> y;
std::copy([Link](), resul
[Link](), std::back_inserter(y));
return y;
}

190 Call an external C


function extern "C" void foo(double *a, int a = (c_int * 10)(*range(10))
Declare an external C n); n = 10
function with the
libc = [Link]('/path/to/c
prototype _library')
[Link](c_void_p(a), c_int(n))
void foo(double *a, int
n);

and call it, passing an


array (or a list) of size
10 to a and 10 to n.

Use only standard


features of your
language.
191 Check if any value in a
list is larger than a limit if (std::any_of([Link](), [Link](), if any(v > x for v in a):
Given a one- [x](auto y) { return y > x; })) f()
dimensional array a,
f();
check if any value is
larger than x, and
execute the procedure f
if that is the case
197 Get a list of lines from a
file std::ifstream file (path); with open(path) as f:
Retrieve the contents of for (std::string line; std::getline lines = [Link]()
file at path into a list of (file, line); lines.push_back(lin
strings lines, in which e)) {}
each element is a line of
the file.
200 Return hypotenuse
Returns the hypotenuse auto h = std::hypot(x, y); h = [Link](x, y)
h of the triangle where
the sides adjacent to
the square angle have
lengths x and y.
205 Get an environment
variable const char* tmp = std::getenv("FO try:
Read an environment O"); foo = [Link]['FOO']
variable with the name std::string foo = tmp ? std::string except KeyError:
C++ Python
"FOO" and assign it to (tmp) : "none"; foo = "none"
the string variable foo. If
it does not exist or if the Alternative implementation:
system does not
foo = getenv('FOO', 'none')
support environment
variables, assign a value
of "none". Alternative implementation:

foo = [Link]('FOO', 'none')

209 Type with automatic


deep deallocation
#include <string> class T:
Declare a type t which using namespace std::string_literal def __init__(self, s, n):
contains a string s and s; self.s = s
an integer array n with
#include <vector> self.n = n
variable size, and #include <memory> return
allocate a variable v of
type t. Allocate v.s and
struct t { v = T('hello world', [1, 4, 9, 16,
v.n and set them to the std::string s; 25])
values "Hello, world!" for std::vector<int> n; del v
s and [1,4,9,16,25],
};
respectively. Deallocate
v, automatically
auto v = std::make_unique<t>(
deallocating v.s and v.n "Hello, world!"s,
(no memory leaks). decltype(t::n){1, 4, 9, 16, 25}
);
[Link]();

// Automatically:
void fn(){
auto v = std::make_unique<t>(
"Hello, world!"s,
decltype(t::n){1, 4, 9, 16,
25}
);
}

211 Create folder


Create the folder at path namespace fs = std::filesystem; [Link](path)
on the filesystem fs::create_directory(path);
212 Check if folder exists
Set the boolean b to auto b = std::filesystem::is_direct b = [Link](path)
true if path exists on the ory(path);
filesystem and is a
directory; false
otherwise.
220 Create a tuple value
Create t consisting of 3 std::tuple<float, std::string, bool t = (2.5, "hello", -1)
values having different > t(2.5f, "foo", false);
types.
Alternative implementation:
Explain if the elements
auto t = std::make_tuple(2.5f, st
of t are strongly typed
d::string("foo"), false);
or not.
222 Find the first index of
an element in list auto it = std::find([Link](), i = [Link](x) if x in items el
Set i to the first index in
[Link](), x); C++ se -1 Python
list items at which the i = it == [Link]() ? std::distan
element x can be found, ce([Link](), it) : -1;
or -1 if items does not
contain x.
223 for else loop
Loop through list items
bool found = false; for item in items:
checking a condition. for (const auto item : items) { if item == 'baz':
Do something else if no if (item == "baz") { print('found it')
matches are found.
baz(); break
found = true; else:
A typical use case is
break; print('never found it')
looping through a series }
of containers looking }
for one that matches a
if (!found) {
condition. If found, an DoSomethingElse();
item is inserted; }
otherwise, a new
container is created. Alternative implementation:

if (std::any_of([Link](), item
These are mostly used
[Link](), condition))
as an inner nested loop,
baz();
and in a location where
else
refactoring inner logic
DoSomethingElse();
into a separate function
reduces clarity.
224 Add element to the
beginning of the list items.emplace_front(x); items = [x] + items
Insert the element x at
the beginning of the list Alternative implementation: Alternative implementation:
items.
items.push_front(x); [Link](0, x)
225 Declare and use an
optional argument void f(std::optional<int> x = {}) { def f(x=None):
Declare an optional std::cout << (x ? "Present" + st if x is None:
integer argument x to d::to_string([Link]()) : "Not Pres print("Not present")
procedure f, printing out ent"); else:
"Present" and its value if } print("Present", x)
it is present, "Not
present" otherwise Alternative implementation:

void f(std::optional<int> x = {}) {


if (x) {
std::cout << "Present" << [Link]
ue();
} else {
std::cout << "Not present";
}
}
C++ Python
226 Delete last element
from list items.pop_back(); [Link]()
Remove the last
element from the list
items.
237 Xor integers
Assign to c the result of int c = a ^ b; c = a ^ b
(a xor b)
239 Find first regular
expression match std::regex re("\\b\\d{3}\\b"); m = [Link](r'\b\d\d\d\b', s)
Assign to string x the
auto it = std::sregex_iterator([Link] x = [Link](0) if m else ''
first word of string s gin(), [Link](), re);
consisting of exactly 3 std::string x = it == std::sregex_i
digits, or the empty
terator() ? "" : it->str();
string if no such match
exists.

A word containing more


digits, or 3 digits as a
substring fragment,
must not match.
242 Iterate over a set
Call a function f on each std::for_each([Link](), [Link](), for e in x:
element e of a set x. f); f(e)

Alternative implementation: Alternative implementation:

for (auto e : x) list(map(lambda e: f(e), x))


f(e);

243 Print list


Print the contents of the std::copy([Link](), [Link](), std:: print(a)
list or array a on the ostream_iterator<int>(std::cout,
standard output. "\n"));

244 Print a map


Print the contents of the for (auto entry : m) { print(m)
map m to the standard
std::cout << [Link] <<
output: keys and values. ": " << [Link] << "\n";
}
245 Print value of custom
type std::cout << x; print(x)
Print the value of object
x having custom type T,
for log or debug.
247 Filter list in-place
Remove all the std::list<Foo> x; del_count = 0
elements from list x x.remove_if(std::not_fn(p)); for i in range(len(x)):
that don't satisfy the if not p(x[i - del_count]):
predicate p, without Alternative implementation:
del x[i - del_count]
allocating a new list. del_count += 1
std::erase_if(x, std::not_fn(p));
Keep all the elements
that do satisfy p.

For languages that don't


have mutable lists, refer
to idiom #57 instead.
C++ Python
251 Parse binary digits
Extract integer value i int i = std::stoi(s, nullptr, 2); i = int(s, 2)
from its binary string
representation s (in
radix 2)
E.g. "1101" -> 13
252 Conditional assignment
Assign to the variable x x = condition() ? "a" : "b"; x = "a" if condition() else "b"
the string value "a" if
calling the function
condition returns true,
or the value "b"
otherwise.
254 Replace value in list
Replace all exact std::replace([Link](), [Link](), "f for i, v in enumerate(x):
occurrences of "foo" oo", "bar"); if v == "foo":
with "bar" in the string x[i] = "bar"
list x
Alternative implementation:

x = ["bar" if v=="foo" else v for v


in x]

256 Count backwards


Print the numbers 5, 4, for (int i = 5; i >= 0; --i) { for i in range(5, -1, -1):
..., 0 (included), one line
std::cout << i; print(i)
per number. }

260 Create an empty list of


strings std::vector<std::string> items; items = []
Declare a new list items
of string elements,
containing zero
elements
271 Test for type extension
If a variable x passed to template<typename T> def tst(x):
procedure tst is of type void tst(T) if type(x) == foo:
foo, print "Same type." If { print("Same type.")
it is of a type that using namespace std; elif isinstance(x, foo):
extends foo, print print("Extends type.")
"Extends type." If it is // Strip away any references an else:
neither, print "Not d pointer print("Not related.")
related." typedef remove_const<remove_poi
nter<decay<T>::type>::type>::type
D;

if(is_same<D, foo>::value)
{
cout << "same type" << end
l;
}
C++
else if(is_base_of<foo, D>::val Python
ue)
{
cout << "extends type" << e
ndl;
}
else
{
cout << "not related" << en
dl;
}
}
272 Play FizzBuzz
Fizz buzz is a children's for(int i = 1; i <= 100; i++) for i in range(1,101):
counting game, and a { if i % 15 == 0:
trivial programming if((i % 15) == 0) std::cout << print("FizzBuzz")
task used to affirm that "FizzBuzz" << std::endl; elif i % 3 == 0:
a programmer knows else if((i % 5) == 0) std::cout print("Fizz")
the basics of a << "Buzz" << std::endl; elif i % 5 == 0:
language: loops, else if((i % 3) == 0) std::cout print("Buzz")
conditions and I/O. << "Fizz" << std::endl; else:
else std::cout << i << std::end print(i)
The typical fizz buzz l;
game is to count from 1 }
Alternative implementation:
to 100, saying each
n=1
number in turn. When Alternative implementation:
while(n<=100):
the number is divisible
for (int n=1; n<=100; n++) { out=""
by 3, instead say "Fizz".
string out=""; if(n%3==0):
When the number is
if (n%3==0)C++{ out=out+"Fizz"
Python
divisible by 5, instead
out=out+"Fizz"; if(n%5==0):
say "Buzz". When the
} out=out+"Buzz"
number is divisible by
if (n%5==0) { if(out==""):
both 3 and 5, say
out=out+"Buzz"; out=out+str(n)
"FizzBuzz"
} print(out)
if (out=="") { n=n+1
out=out+std::to_string
(n); Alternative implementation:
}
cout << out << "\n"; for i in range(100, 1):
} if i % 5 == 0 and not i % 3 ==
0:
print(i, "Buzz");
if i % 3 == 0 and not i % 5 ==
0:
print(i, "Fizz");
if i % 3 == 0 and i % 5 == 0:
print(i, "FizzBuzz");

Alternative implementation:

for i in range(1, 100+1):


out = ""
if i % 3 == 0:
out += "Fizz"
if i % 5 == 0:
out += "Buzz"
print(out or i)
275 Binary digits to byte
array const size_t n = [Link]() / 8; n = (len(s) - 1) // 8 + 1
From the string s a = bytearray(n)
consisting of 8n binary vector<uint8_t> a(n); for i in range(n):
digit characters ('0' or b = int(s[i * 8:(i + 1) * 8],
'1'), build the equivalent for(size_t block = 0; block < n; bl 2)
array a of n bytes. ock++) a[i] = b
Each chunk of 8 binary {
digits (2 possible values uint8_t acc = 0;
per digit) is decoded const size_t start = block * 8;
into one byte (256 for(size_t offset = start; offs
possible values). et < start + 8; offset++)
{
acc = (acc << 1) + (s[offse
t] - '0');
}

a[block] = acc;C++ Python


}

277 Remove an element


from a set [Link](e); [Link](e)
Remove the element e
from the set x.

Explains what happens


if e was already absent
from x.
278 Read one line from the
standard input int main() { line = [Link]()
Read one line into the for (std::string line; std::get
string line.
line(std::cin, line);) {
std::cout << line << std::e
Explain what happens if
ndl;
EOF is reached. }
return 0;
}

280 Filter map


Remove all the for (auto it = [Link](); it != m.e m = {k:v for k, v in [Link]() if p
elements from the map nd();) { (v)}
m that don't satisfy the if (!p(it->second)) {
predicate p. it = [Link](it);
Alternative implementation:
Keep all the elements } else {
++it; for k in list(m):
that do satisfy p.
} if p(m[k]): [Link](k)
Explain if the filtering }
happens in-place, i.e. if
m is reused or if a new
map is created.
284 Create a zeroed list of
integers std::vector<int> a(n, 0); a = [0] * n
Create a new list a (or
array, or slice) of size n,
where all elements are
integers initialized with
the value 0.
288 Check if set contains a
value b = [Link](e) != [Link](); b = e in x
Set the boolean b to
true if the set x contains
the element e, false
otherwise.
289 Concatenate two
strings std::string a{"Hello"}; s = a + b
Create the string s by std::string b{"world"};
concatenating the auto s = a + b;
strings a and b.
299 Comment out a single
line // This is a comment. # This is a comment
Write a line of
comments.

This line will not be C++ Python


compiled or executed.
302 String interpolation
Given the integer x = 8, s = std::format("Our sun has {} pla s = f'Our sun has {x} planets'
assign to the string s nets", x);
the value "Our sun has 8
planets", where the
number 8 was
evaluated from x.
313 Map equality
Set b to true if the maps b = m == n; b = m == n
m and n have the same
key/value entries, false
otherwise.
314 Fill array with value
Set all the elements in [Link](v); x[:] = [v] * len(x)
the array x to the same
value v
320 Test if string is empty
Set b to true if the string b = [Link](); b = s == ''
s is empty, false
otherwise
322 replace value of
variable with new one std::exchange(x, v); old, x = x, new
and return old value

You might also like