C++
This document summarizes snippets and useful C++ features categorized by C++ version.
C++11
Lambda functions
;
Recursive lambda functions:
std::function<int> fibonacci = ;
foreach-style loops
for
std::map<std::string, int> map;
for
std::begin() and std::end()
int array = ;
;
auto
With auto
, the compiler has to guess the type of a variable.
std::map<std::string, int> map;
for
auto
can be used as a return type of a function in this case:
auto decltype
auto value = ;
List initialization
std::map<std::string, int> = ;
nullptr
The keyword nullptr
represents a null pointer.
int * p = nullptr;
if
Move and copy
A class has 5 default operations:
- copy constructor
- move constructor
- destructor
- copy assigment
- move assignment
;
override and final
To explicitly inform that a method overrides a virtual method. Makes the code more understandable.
The keyword final
makes a method impossible to override.
;
;
;
default and delete
You can specify a default copy behavior using default
.
;
You can forbid copying an object using delete
.
;
delete
can be used for any function, for example to forbid an argument type conversion.
;
Initialize a vector of indices from 0 to n-1 and sort it according to another vector
::vector<std::size_t> ;
// indices = [0, 0, 0, ..., 0]
;
// indices = [0, 1, 2, ..., n-1]
;
// indices are sorted by increasing values
std
C++14
auto lambda function arguments
Lambda functions can be declared without explicit argument types.
auto lambda = ;
auto return type
auto
If a function has multiple return
, all of them have to be of the same type.