C++, Python Cheat Sheet
C++, Python Cheat Sheet
print('Hello World')
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
Alternative implementation:
Alternative implementation:
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}
};
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{}
()});
Alternative implementation:
Alternative implementation:
Alternative implementation:
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)
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);
}
}
}
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);
std::sort(begin(items), end(items),
custom_sort);
//use
{
auto lock = std::unique_loc
k{mutex};
x = f(x);
}
class T:
...
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);};
}
Alternative implementation:
//function
auto add(int a, int b) -> int {
return a + b;
}
//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
Alternative implementation:
while (true) {
// Do something
}
Alternative implementation:
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";
}
Specify if i should be
regarded as a character
index or as a byte index.
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:
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.
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.
bool b = s.ends_with(suffix);
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());
print_map_contents(map);
}
if(x == a[mid])
{
return C++
(int)mid; Python
}
else if(x > a[mid])
{
lower = mid + 1;
}
else
{
upper = mid - 1;
}
}
return -1;
}
Alternative implementation:
auto foo()
{
return std::make_tuple("Hello",
true);
}
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;
}
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]();
Alternative implementation:
f = float(s)
Alternative implementation:
f = float(s)
[Link](filepath)
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;
});
return n;
}
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,
};
}
for_each(begin(i), end(i),
[&](const auto& x) {
if(p(x))
o.push_back(f(x));
}
);
return o;
} C++ Python
Alternative implementation:
std::vector<std::ranges::range_
value_t<decltype(result)>> y;
std::copy([Link](), resul
[Link](), std::back_inserter(y));
return y;
}
// Automatically:
void fn(){
auto v = std::make_unique<t>(
"Hello, world!"s,
decltype(t::n){1, 4, 9, 16,
25}
);
}
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:
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: