Computational complexity is a concept in computer science and the theory of algorithms, denoting the dependence function of the amount of work,
which is performed by some algorithm, depending on the size of the input data.
In asymptotic analysis, the complexity of an algorithm is a function to determine whether
how quickly the running time of the algorithm increases with the increase in the amount of data.
f(n) = O(1) constant
f(n) = O(log(n)) log growth
f(n) = O(n) linear growth
f(n) = O(n*log(n)) quasi-linear growth
f(n) = O(n^m) polynomial growth
f(n) = O(2^n) exponential growth
O - means the upper bound on the complexity of the algorithm.
search algorithms - linear, recursive, half division for sorted
Bubble sort We will go through the array from left to right. If the current element is greater than the next, swap them. Then again
Shaker sort / Shaker sort Therefore, we will go not only from left to right, but also from right to left.
At the next iteration, when end is reached, we subtract one from it and move from right to left, similarly,
when begin is reached, we add one and move from left to right
The comb will rearrange the elements standing at a distance. in increments of 1.27
Insertion sort insert elements from the source array so that the elements in the response array are always sorted
Shellsort We use the same idea as comb sort and apply to insertion sort.
Tree sort / Tree sort We will insert elements into a binary search tree multiset m;
Quick sort / Quicksort Let's choose some basic element. After that, we will throw all the elements smaller than it to the left,
and large ones to the right. Recursively call from each of the parts
Selection sort
At the next iteration, we will find the minimum in the array after the current element and change it with it, if necessary. Thus, after the i-th iteration, the first i elements will be in their places.
std::sort - introsort O(nlog(n)) in worse and average case
it is inplace and unstable
hybris sorting algorithm (quick sort + heapsort then num elements less 16)
heapsort nlog(n) sorted and unsorted ranges, put data ranges in heap structure std::partial_sort()
std::stable_sort() - n log n if we have memory
std::list::sort(), std::forward_list::sort()
A binary search tree is a binary tree that has additional properties: the value of the left child is less than the value of the parent,
and the value of the right child is greater than the value of the parent for each tree node.
That is, the data in the binary search tree is stored in sorted form.
in C++, the associative containers set and map represent a balanced binary search tree.
A balanced binary search tree is a binary search tree with a logarithmic height.
In a balanced binary search tree, searches, insertions, and deletions take logarithmic time.
(since the path to any leaf from the root is no more than a logarithm).
In the degenerate case of an unbalanced binary search tree, such as when a sorted sequence was inserted into an empty tree,
the tree would become a linear list, and the search, insertion, and deletion operations would take linear time.
Let's briefly discuss trees from the point of view of graph theory. A graph is a set of vertices and edges. An edge is a connection between
two vertices.
The number of possible edges in the graph depends quadratically on the number of vertices (for understanding,
you can imagine the tournament table of matches played).
A tree is a connected graph without cycles. Connectivity means that from any vertex to any other there is a path along the edges.
The absence of cycles means that this path is the only one. Traversing a graph is a systematic visit to all its vertices, once each.
There are two types of graph traversal: 1) depth-first search; 2) breadth-first search.
breadth-first search (BFS) starts from the start vertex, first visits all vertices that are one edge away from the start,
then it visits all vertices two edges away from the initial one, and so on.
The breadth-first search algorithm is non-recursive (iterative) in nature.
To implement it, a queue data structure (FIFO) is used.
Depth-First Search (DFS) proceeds from the initial vertex, visiting vertices that have not yet been visited, regardless of the distance
from the initial vertex.
The depth-first search algorithm is recursive in nature.
To emulate recursion in the iterative version of the algorithm, the stack data structure is used.
A hash table is a special data structure for storing pairs of keys and their values.
In fact, this is an associative array in which the key is represented as a hash function.
Perhaps the main property of hash tables is that all three insertion, lookup, and deletion operations are performed on average in O(1) time,
the average search time for it is also O(1) and O(n) in the worst case.
Properties of red-black trees:
1) Each node is colored either red or black (an additional field appears in the node data structure - a color bit).
2) The root is painted black.
3) Leaves (so-called NULL nodes) are painted black.
4) Each red node must have two black children. It should be noted that a black node can have black children. Red nodes can only have black nodes as children.
5) Paths from a node to its leaves must contain the same number of black nodes (this is the black height).
An associative array is an abstract data type (an interface to a data store) that allows you to store pairs of the form "(key, value)" and
supports the operations of adding a pair, as well as searching and deleting a pair by key:
INSERT(key, value)
FIND(key)
REMOVE(key)
It is assumed that an associative array cannot store two pairs with the same keys.
Compilation stages
1) Preprocessing
2) Compilation converts the code obtained at the previous step without directives into assembler code.
3) Assembly
4) The linker (linker) links all object files and static libraries into a single executable file,
A symbol table is a data structure created by the compiler itself and stored in the object files themselves.
The symbol table stores the names of variables, functions, classes, objects, etc., where each identifier (symbol) corresponds to its type, scope.
The symbol table also stores the addresses of links to data and procedures in other object files.
It is with the help of the symbol table and the references stored in them that the linker will be able to further build links between
data among many other object files and create a single executable file from them.
// copy assignment
T& operator=(const T& other)
{
// move assignment
T& operator=(T&& other) noexcept
{
A functor (function object) is an object that can be used like a function.
class Square{
public:
int operator() (const int value) const{
return value * value; //
}
};
A template declaration with a variable number of parameters looks like this:
template
class VariadicTemplate
{
};
Lambda is just an anonymous function.
A closure is a function that uses objects from the environment in which it was declared. In the second line of the previous example,
the equal sign stands for "context capture".
Not all lambdas are closures, and not all closures are lambdas.
Closures in C++ are ordinary objects that can be called.
Closures do not extend the life of the objects they use (you need to use shared_ptr for that).
List folding (English folding, also known as reduce, accumulate) in programming is a higher-order function,
which converts the data structure to a single atomic value using the given function.
cpp17 innovations
convolution
template
std::string linearBitsUnrolling()
{
std::string bits;
((bits += bitToString()), ...);
return bits;
}
template
constexpr int sum()
{
return (values + ...);
}
template
std::string linearBitsUnrolling()
{
std::string bits;
(bits += ... += bitToString());
return bits;
}
template
std::string linearBitsUnrolling()
{
std::string bits;
(bits += ... += bitToString());
return bits;
}
RunTime Type Information RTTI
typeid if (typeid(*left) == typeid(*right)) return true;
typeinfo
dynamic cast(pointer) if not 0 then you can cast
Suppose we have allocated in memory an object of some complex class with multiple inheritance.
Then, as we already know, pointers of different types to the same object can store different addresses.
The dynamic_cast casting operator for some object returns the smallest address of all possible addresses for this object,
those. address of its first byte
return (dynamic_cast(p) == dynamic_cast(q));
static_cast
Static Cast: This is the simplest type of cast which can be used.
It is a compile time cast.
It does things like implicit conversions between types (such as int to float, or pointer to void*),
and it can also call explicit conversion functions (or implicit ones).
const_cast
const_cast is used to cast away the constness of variables.
reinterpret_cast
It is used to convert a pointer of some data type into a pointer of another data type,
even if the the data types before and after conversion are different.
It does not check if the pointer type and data pointed by the pointer is same or not.
typedef int*(*ret)(char const*);
typedef int (*arg)(double);
typedef ret (*ComplexFunction)(int, arg);
double (Elf::*)(unsigned) const
Unit const * (Archer::*)
unsigned (Unit::*mtd)() const = &Unit::id;
unsigned Unit::*fld = &Unit::hp;
Unit u;
Unit * p = &u;
(u.*mtd)() == (p->*mtd)();
(u.fld) = (p->*fld);
pointer to f-th == function address
field pointer == offset relative to the start of the object
method pointer == method address, virtual table number, offset
decltype(z) type z
decltype((z)) reference
auto value - drop reference
с++14 decltype(auto) reference
constexpr - compilation stage
constexpr Point(double x, double y)
std::function
op;
u8 UTF-8 string
u UTF-16
U utf-32
& && = &
& & = &
&& & = &
&& && = &
universal reference:
foo (T && x)
perfect forwarding
std::forward()
template
auto apply(T func, Args&&... args)->decltype(func(std::forward(args)...))
{
return func(std::forward(args)...);
}
std::forward() we save the method of passing to the internal function (it was l-value, so it will be l-value for example)
pointing to a permanent class method
double (Elf::*)(unsigned) const
pointer to the archer class field
Unit constant * (Archer::*)
The traits class is called a template class,
providing for its parameter a set of some basic definitions,
as a rule of types and constants, which in some way characterize the type substituted into the characteristic class as a template parameter.
A tag class is a class that
containing no members (empty),
serving only as a nominal value (constant name).
The fact that it is a type and not a value allows it to be used when choosing a particular variant
of an overloaded function (see below for examples of tagged classes in the context of iterators).
Tagged classes can be in inheritance relationships.
STL:
containers
iterators
adapters (wrappers over containers)
algorithms (for working with sequences)
functional objects - functors
containers serial
swap, max_size, empty, clear, begin, end, cbegin, cend
comparison operators
Array (at - array out of bounds check)
rest
constructor(count,defVal), std::initializer_list
back, front, push_back, emplace_back, assign, insert, emplace, erase
erase from one or two iterators
deque-
list of pointers to arrays of fixed size
fast insertion and removal at O(1) ends:
list - doubly linked list (anywhere) - no dos
forward_list - O(1) insertion and deletion
adapters:
stack,queue,priority_queue
Associative Containers
ordered (require an order relation) and unordered (require a hash function - collation)
find by key count by key erase by key
set - ordered set as a balanced binary search tree O(logn) add and lookup, values are immutable
multiset repeating elements
map, multimap - search tree by key std::pair
iterators
advance(it, n) by n positions
distance(it1, it2)
iter_swap(it1, it2) - swap values
std::next, std::prev
invalidation invalidates any container (vector & string) can do anything (new buffer allocation)
copy(it1,it2, ostream_iterator(cout,"\n"))
extra parentheses - in order to separate the constructor from the function
unique_ptr
smart pointer with unique ownership
cannot be copied can be moved
not suitable for shared objects
unique_ptr
smart pointer with unique ownership
can't be copied can be moved
not suitable for shared objects
shared_ptr
smart pointer with reference counting
universal pointer
weak_ptr
smart pointer to create weak links
This is exactly what a weak pointer does - it allows you to find an object if it's still around,
but doesn't support it if it doesn't need anything else.
Instead, allowing std::shared_ptr to manipulate the data and
supplying std::weak_ptr to data users,
users can check the validity of the data,
calling expired() or lock()
weak_ptr
parentWeakPtr_ = parentSharedPtr;
// automatic conversion to weak from shared
if(auto tmp = weak1.lock())
std::cout << *tmp << '\n';
else
std::cout << "weak1 is expired\n";
auto g = bind(f, _1, 4, _2) // g special case f
algorithms
Non-modifiers take sequence and predicate
all_of(true for all), any_of, none
for_each (for loop
find (sequence and first value)
find_first_of - occurrence of one of the elements in the first sequence
and looks for the first occurrence (no end of sequence)
adjacent_find (compares pairs of adjacent elements)
count, count_if - number of occurrences
equal, mismatch - first mismatch in sequence
is_permutation - the first is a permutation of the second
lexicographical_compare - lexicographical comparison
search, search_n(search for 3 sevens), find_end(last occurrence) - search for the second sequence as a substring
Ordered Sequences
lower_bound, upper_bound, equal_range
looking for sequence boundaries
Sets
set_intersection, set_difference, set_union,
set_symmetric_difference
bynary_search, includes
Modifying algorithms:
fill, fill_n, generate, generate_n (functor)
filling sequences
random_shuffle, shuffle - permutation of sequences
copy, copy_n, copy_if, copy_backward (copies from the end)
move, move_backward
remove, remove_if, remove_copy, remove_copy_if(remove)
replace, replace_if, remove_copy, remove_copy_if
reverse, reverse_copy
rotate,rotate_copy - cyclic shift
swap_ranges - swap ranges
TRANSFORM - elementwise operation with 2 sequences
unique, unique_copy
remove consecutive identical elements
accumulate sum of elements e.g.
adjacent_difference difference of pairs
inner_product dot product
partial_sum
iota - 0 to n fills
vector.erase(remove(v.beg,v.end,5), v.end())
list.remove(5);
Removing from associative containers
you cannot erase(it) because the iterator is immediately invalidated and cannot be incremented
it = map.erase(it) else ++it
sorting algorithms
is_sorted, is_sorted_until
sort, stable_sort
(keep elements that are the same with respect to ordering)
nth_element - nth element
partial_sort - partial sort (first five smallest)
merge - merge sequences
partition, stable_partition, is_partitioned, partition_copy, partition_point
Metaprogramming (Boost MPL)
use typename to indicate that the type is being specified
SFINAE = Substitution Failure is Not An Error
template
struct is_foo_defined
{
template
struct wrapper{};
template
static YES check(wrapper * p);
template
static NO check(...)
static bool const value =
sizeof(YES) == sizeof(check(0));
}
template
typename std::enable_if<
std::is_integral::value, T>::type
div2(T t) {return t>>1;}
template
typename std::enable_if<
std::is_floating_point::value, T>::type
div2(T t) {return t / 2.0;}
////////////////////////////////////////////
COUSERA
////////////////////////////////////////////
#define ASSERT_EQUAL(x,y) {\
ostringstream os; \
os << #x << " != " << #y << ", " << __FILE__ << __LINE__;\
AssertEqual(x,y,os.str());}\
throw runtime_error(os.str());
g++ -E -
using std::chrono;
time ./prog
yandex:
auto start = steady_clock::now(); - in constructor
auto finish = steady_clock::now(); - in destructor
cerr << duration_cast(finish-start).count()
wrap calculations in quotes and declare a class
{ Timetime; {}}
profilers
-gperftools(Linux, Mac OS)
- perf (Linux)
-Vtune (Win)
explicit constructor(string) -
for that
to avoid implicitly converting their string to a class
class LogDuration {
public:
explicit LogDuration(const string& msg = "")
: message(msg + ": ")
, start(steady_clock::now())
{
}
~LogDuration() {
auto finish = steady_clock::now();
auto dur = finish - start;
cerr << message
<< duration_cast(dur).count()
<< " ms" << endl;
}
private:
string message;
steady_clock::time_point start;
};
copy constructor should be written when your class manages memory itself
SimpleVector(const SimpleVector & other):data(new T[other.capacity]){}
moving
SimpleVector(SimpleVector && sv) = default; // ????? bad if there is an object in dynamic memory
template
SimpleVector :: SimpleVector(SimpleVector && other)
:data(other.data),size(other.size),capacity(other.capacity)
{
other.data=nullptr;
other.size = other.capacity = 0;
}
move operator
template
void SimpleVector :: operator(SimpleVector && other)
{
delete[] data;
data = other.data;
size = other.size;
capacity = other.capacity;
other.data=nullptr;
other.size = other.capacity = 0;
}
move rules in container:
data.insert(move(object));
erase copy constructor
SimpleVector(const SimpleVector & ) = delete;
copy elision -
lack of creation of copying and moving, in case of creating temporary objects due to optimization
compiler
name return value optimization NRVO
const vector sn = Sorted({1,3,7,6});
std::binary_search(begin(sn),end(sn),x)
constancy in classes allows you to maintain
immutability, error checking,
maintaining the ability to use special methods
unique elemeni in vector:
auto it = unique(begin(data), end(data));
data.erase(it, end(data));
idiom IILE
immediately invoked lambda expression
const int non_negative_value = []{}{return smf;}();
fields marked mutable - these fields can be changed,
even in a const class (like cache or mutable)
for multithreaded output first use sstringstream << message
and after it in cout
operations with shared_ptr from 2 threads
safe copy get() ->
unsafe move reassign
you need to worry about the object, and you should make it constant if possible
An object can be deleted even if there are weak_ptr referencing it
weak_ptr g(&h);
auto dummyDeleter = [](Widget*){};
return shared_ptr (ptr, dummyDeleter);
Resource Acquisition Is Initialization (RAII)
linux interprocess communication
named pipe pipe int mkfifo(const char *pathname, mode_t mode);
shared memory
int shm_open(const char *name, int oflag, mode_t mode);
named semaphore
sem_t *sem_open(const char *name, int oflag, mode_t mode, unsigned int value);
+ signal, socket
polymorphism
One interface, many methods.
static polymorphism can be achieved by template functions
End action is determined at compile time
runtime polymorphism can be achieved by virtual functions
End action is determined at run time
static_cast between pointers is correct only if one of the pointers is
is a pointer to void or if it is a cast between class objects,
where one class is an inheritor of another. That is, to cast to any type from void*,
which malloc returns, static_cast should be used.
If the cast fails, a compile-time error will occur.
However, if this cast is between pointers to class objects down the hierarchy and it fails,
the result of the operation is undefined. That is, such a cast is possible: static_cast(pBase),
even if pBase does not point to Derived, the program will still behave strangely.
dynamic_cast<>
Safe cast along the inheritance hierarchy, including for virtual inheritance.
dynamic_cast(base_class_ptr_expr)
RTTI (Runtime Type Information) is used to cast one pointer to a class object to another pointer to a class object.
Classes must be polymorphic, that is, the base class must have at least one virtual function.
If these conditions are not met, a compile-time error will occur.
If the cast is not possible, then this will become clear only at the stage of program execution and NULL will be returned.
dynamic_cast(base_class_ref_expr)
Working with links is almost like working with pointers,
but in case of a runtime error, a bad_cast exception will be thrown.
for (char a : s)
if (j.find(a) != std::string::npos) count++;
//////////// mail.ru
CRTP Curiously recurring template pattern
template
class Base
{
};
class Derived : public Base
{
};
linux epol
https://habr.com/ru/post/416669/
10k connections epoll - libevent
split to words
1
string s = "Somewhere down the road";
istringstream iss(s);
do
{
string subs;
iss >> subs;
cout << "Substring: " << subs << endl;
}while (iss);
2
std::regex regex("[a-zA-Z]+");
for (std::sregex_token_iterator it(begin(input), end(input), regex), last; it != last; ++it){
std::string ss = it->str();
//words.push_back(ss);
}
saving to file
#include
#include
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile.close();
FlyWeight - Flyweight
The Flyweight pattern shows how to effectively separate many small objects.
The key concept is the distinction between internal and external states.
The internal state consists of information that is context independent and can be shared (for example, the name of an icon, its width and height).
It is stored in the flyweight (that is, in the Icon class).
External state cannot be shared, it depends on the context and changes with it
(for example, the coordinates of the top left corner for each instance of the icon).
The external state is stored or computed by the client and passed to the flyweight when the operations are called.
Clients should not instantiate flyweights directly, but only obtain them from the FlyweightFactory object for proper partitioning.
False sharing
When a member of the system periodically attempts to access data,
which will never be changed by the other party,
but this data shares a cache block with the data,
that have been changed, the caching protocol can force the first participant to reload the entire block,
despite the lack of logical necessity. .
The caching system is unaware of the activity in this block and causes the first participant to bear the overhead of the caching system,
necessary for true sharing of the resource.
SOLID
Object-oriented programming
The Single Responsibility Principle
a class should only do one thing
and have only one reason to change it
Open Closed Principle
the class is open to extensions and closed to modifications
Liskov Substitution Principle
subclasses must be inline in place of base classes
Interface Segregation Principle
many client-specific functions in an interface are better than one generic interface
Dependency Inversion Principle
classes must be dependent on interfaces
https://en.cppreference.com/w/cpp/language/rule_of_three
Rule of three
If a class requires a user-defined destructor, a user-defined copy constructor,
or a user-defined copy assignment operator, it almost certainly requires all three.
rule_of_three(const rule_of_three& other) // II. copy constructor
: rule_of_three(other.cstring) {}
rule_of_three& operator=(const rule_of_three& other) // III. copy assignment
{
Rule of five
Because the presence of a user-defined (or = default or = delete declared) destructor, copy-constructor, or copy-assignment operator
prevents implicit definition of the move constructor and the move assignment operator,
any class for which move semantics are desirable, has to declare all five special member functions:
rule_of_five(rule_of_five&& other) noexcept // move constructor
: cstring(std::exchange(other.cstring, nullptr)) {}
rule_of_five& operator=(const rule_of_five& other) // copy assignment
{
return *this = rule_of_five(other);
}
rule_of_five& operator=(rule_of_five&& other) noexcept // move assignment
{
std::swap(cstring, other.cstring);
return *this;
}
is usually not an error, but a missed optimization opportunity.
Rule of zero
class rule_of_zero
{
std::string cppstring;
public:
rule_of_zero(const std::string& arg) : cppstring(arg) {}
};
class base_of_five_defaults
{
public:
base_of_five_defaults(const base_of_five_defaults&) = default;
base_of_five_defaults(base_of_five_defaults&&) = default;
base_of_five_defaults& operator=(const base_of_five_defaults&) = default;
base_of_five_defaults& operator=(base_of_five_defaults&&) = default;
virtual ~base_of_five_defaults() = default;
};
////////////// END //////////////