Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
C++ 11
Language enhancements and additions
Telerik Software Academy
Learning & Development Team
http://academy.telerik.com
Table of Contents (1)
1.
Runtime performance enhancements
Rvalue references and move constructors
Generalized constant expressions
2.
Usability enhancements
Initializer lists
Type inference
Range based for loop
Lambda functions and expressions
Null pointer constant
Right angle bracket
2
Table of Contents (2)
3.
Standard Template Library
Tuple types
Hash tables
Extensible random number facility
4.
Algorithms
Non-modifying / modifying sequence
Sorting, minmax, heaps
Rvalue references
T&& and move constructor
Rvalues
Lvalues
(references)
Lie on the left side of assignments
Identified by T&
Rvalues (temporaries)
Lie on the right side of assignments
Identified by T&&
Make move semantics possible
Rvalues
Move constructors
on STL containers:
Given a really big string (1GB)
string str(1<<30);
Copies the big string
Slow and allocates another 1GB of memory
string str_copied = str;
Moves the contents of str to str_moved
Fast and doesn't allocate another 1GB of memory
str will be an empty string after the assignment
string str_moved = move(str);
6
Rvalues
Move semantics on STL containers:
string append_char(string str, char ch) {
str += ch;
return move(str);
}
// Really big string (1GB)
string str(1<<30);
string str2 = append_char(move(str), '5');
7
Constant expressions
constexpr keyword
Constexpr
Allows constant expressions to be functions
// Array size must be a compile time constant
int A[5+10*23];
// constexpr keyword guarantees that
// a function is a compile time constant
constexpr int square(int x) {
return x*x;
}
int B[square(10)];
Restrictions (more relaxed in C++ 14)
Function must be non-void
Variables can not be declared
Types can not be defined
Only one statement allowed (return value)
Initializer lists
Initializing arrays, containers and other structures
Initializer lists
Initializer
list ({value, value, … })
Type initializer_list can be cast to:
STL containers
Pairs and tuples
Custom structures
Can be nested
"=" can be omitted ( uniform initialization )
Initializer lists
Examples:
int array[] = {1, 3, 2, 5, 7}; // from C
vector<int> v = {1, 3, 2, 5, 7};
v = {1, 2, 3};
set<int> s = {1, 3, 2, 5, 7};
pair<int, int> SumAndDif(int a, int b) {
return {a+b, a-b};
}
map<string, int> Map = {
{"banana", 3},
{"apple", 7},
{"cherry", -5}
};
12
Initializer lists
Examples:
struct rgb {
double red;
double green;
double blue;
}
// Can be used on custom structures
rgb color = {1.0, 0.5, 0.0};
// Can be nested
vector<rgb> colors = {
{0, 0, 0},
{1, 1, 1},
{0.5, 0, 1},
{0.2, 0.8, 0.4}
};
13
Type inference
auto, decltype
Type inference
Auto (auto
variable = value)
Deduces type for variable from value
Does not deduce const types
Does not deduce reference (&) types
Decltype (declype(expression))
This is the type of the expression
Can deduce const types
Can deduce reference types
15
Type inference
Examples:
int a0;
auto a1
auto a2
auto a3
auto a4
// int (apparently)
= a0; // int
= 7; // int
= 7-a0*(13+a1); // int
= 2ll; // long long
const char c0 = 'x'; // const char (apparently)
auto c1 = c0; // char (non-const)
const auto c2 = c0; // const char
char &r0 = c1; // char& (apparently)
auto r1 = r0; // char (non-reference)
auto &r2 = r0; // char&
int *p0 = &a0; // int* (apparently)
auto p1 = p0; // int*
Type inference
Useful when working with iterators
map<string, int> Map;
for (map<string, int>::iterator it = Map.begin();
it != Map.end(); ++it) {
cout<< it->first <<" -> "<< it->second <<'\n';
}
// becomes
for (auto it = Map.begin(); it != Map.end(); ++it) {
cout<< it->first <<" -> "<< it->second <<'\n';
}
Type inference
Examples:
int a;
// decltype(a) is int
// decltype((a)) is int&, because (a) is an lvalue
// decltype(0) is int, because 0 is an rvalue
const vector<int> v(1);
// decltype(v[0]) is const int&
Range based loops
Iterating over arrays and containers
Range based loops
Iterating over range of elements
C style arrays
STL containers
Initializer lists
Any type with defined begin() and end() functions
20
Range based loops
Accessing all elements
int A[10] = {1, 5, 9, 2, 4, 0, 2, 2, 7, 9};
for(int x:A) {
cout<<x<<'\n';
}
Modifying all
elements
int A[10] = {1, 5, 9, 2, 4, 0, 2, 2, 7, 9};
for(int x:A) { // Copies each element in x
x *= 2; // A is not modified
}
for(int &x:A) { // Using reference
x *= 2; // A is modified
}
Range based loops
Can be used on STL containers
vector<string> = {"Pencil", "Knife", "Ball"};
for(string &x:A) {
reverse(x);
}
Combining with auto
map<string, int> Map;
for (pair<string, int> &x:Map) {
cout<<x.first<<" -> "<<x.second<<'\n';
}
// becomes
for (auto &x:Map) {
cout<<x.first<<" -> "<<x.second<<'\n';
}
Lambda functions
Definition and usage
Lambda functions
[](int
x,int y) { return x+y; }
Return type is decltype(x+y)
Variable
capture
[]
[variable]
[&variable]
[&]
[=]
24
Lambda functions
Examples:
vector<int> v;
sort(v.begin(), v.end(), [](int x, int y) {
return abs(x) < abs(y);
});
int n; cin >> n;
sort(v.begin(), v.end(), [&n](int x, int y) {
return x%n < y%n;
});
Null pointer constant
nullptr constant
Null pointer constant
nullptr – Constant
of type nullptr_t
Can be cast to any pointer type
Can not be cast to integer types
Can be cast to bool ( it's false )
void f(int);
void f(char*);
// NULL is defined as 0 which is int
f(NULL); // calls f(int) – Wrong
f(nullptr); // calls f(char*) – Correct
27
Space Between
Right-angle brackets
Nested template declarations
Before C++ 11 ">>" is always defined as right shift
C++ 03 and before
vector<vector<int> > items
C++ 11
vector<vector<int>> items
Space Between
Right-angle brackets
Nested template declarations
Before C++ 11 ">>" is always defined as right shift
C++ 03 and before
vector<vector<int> > items;
Space required
before C++ 11
C++ 11
vector<vector<int>> items;
Space not required
in C++ 11
Tuples
Creating and using tuples
Tuple
Tuple (#include
<tuple>)
Creating tuples
tuple<type1, type2, ...> t;
tuple<type1, type2, ...> t(value1, value2, …);
tuple<type1, type2, ...> t{value1, value2, …};
make_tuple(value1, value2, …);
Accessing tuple elements (get)
Unpacking tuples (tie, ignore)
Concatenating tuples (tuple_cat)
31
Tuples
Examples:
tuple<int, string, bool> tup(42, "hamster", true);
cout << get<0>(tup); // cout's 42
cin >> get<1>(tmp); // cin's a string
get<2>(tmp) = false;
// Unpacking the tuple in
// num and str, ignoring the Boolean
// tie creates a tuple of references
int num;
string str;
tie(num, str, ignore) = tup;
Tuples
Examples:
tuple<int, string, bool> tup(42, "hamster", true);
int n = 17;
auto tup2 = tuple_cat(tup, make_tuple(3.5), tup, tie(n));
// tup2 is of type tuple<int, string, bool, double,
int, string, double, int&>
n = 19; // last element in tup2 is reference to n
// (42, "hamster", true, 3.5, 42, "hamster", 19)
Hash tables
Unordered_(multi)set, unordered_(multi)map
Hash tables
Unordered_(multi)set, unordered_(multi)map
Same as (multi)set and (multi)map
but unordered
Key must have defined Hash function instead of
Compare
Extracting elements one by one:
Yields the elements in some order
Hash tables
Unordered_(multi)sets (#include<unordered_set>)
unordered_set<Key,
Hash = hash<Key>,
Alloc = new>
Unordered_(multi)maps (#include<unordered_map>)
unordered_map<Key, Value
Hash = hash<Key>,
Alloc = new>
Constant average times for operations
36
Random number facility
Random number generators and distributions
Random numbers
Non-deterministic numbers
random_device
Random number engines
Predefined generators
Engine adaptors
Distributions
Uniform
Normal
Others
38
Random number generators
linear_congruential_engine
minstd_rand
minstd_rand0
mersenne_twister_engine
mt19937
mt19937_64
subtract_with_carry_engine
ranlux24_base
ranlux48_base
Random number generators
adaptors
discard_block_engine
ranlux24
ranlux48
independent_bits_engine
shuffle_order_engine
knuth_b
Random number generators
Examples:
#include <random>
using namespace std;
int main() {
random_device rd;
// get a random number
cout << rd() << '\n';
mt19937 gen(seed); // seed can be rd()
// get a pseudo-random number
cout << gen() << '\n';
}
Random number distributions
Uniform distributions
uniform_int_distribution
uniform_real_distribution
generate_canonical
Normal distributions
normal_distribution
Others
Others
Random number distributions
Examples:
mt19937 gen{random_device{}()}; // generator
uniform_int_distribution<int> dice(1, 6);
// Gives number from 1 to 6 with equal probability
dice(gen);
uniform_real_distribution<double> reals(0.0, 10.0);
// Evenly distributed real numbers from 0 to 10
reals(gen);
normal_distribution<double> gauss(42, 5);
// Numbers close to 42 will be most probable
// 5 is standard deviation
gauss(gen);
Algorithms
New algorithms in <algorithm>
Algorithms
Non-modifying sequence operations
all_of(first, last, predicate)
any_of(first, last, predicate)
none_of(first, last, predicate)
Modifying sequence operations
move(first, last, d_first)
move_backwards(first, last, d_last)
shuffle(begin, end, generator)
Uses the new random number functionality
Replaces random_shuffle
45
Algorithms
Sorting operations
is_sorted(begin, end)
is_sorted_until(begin, end)
Min/max operations
minmax(a, b)
minmax_element(begin, end)
is_permutation(first1, last1,
first2, last2)
Heap operations
is_heap(begin, end)
is_heap_until(begin, end)
46
C++ 11 Overview
курсове и уроци по програмиране, уеб дизайн – безплатно
курсове и уроци по програмиране – Телерик академия
уроци по програмиране и уеб дизайн за ученици
програмиране за деца – безплатни курсове и уроци
безплатен SEO курс - оптимизация за търсачки
курсове и уроци по програмиране, книги – безплатно от Наков
уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop
free C# book, безплатна книга C#, книга Java, книга C#
безплатен курс "Качествен програмен код"
безплатен курс "Разработка на софтуер в cloud среда"
BG Coder - онлайн състезателна система - online judge
форум програмиране, форум уеб дизайн
ASP.NET курс - уеб програмиране, бази данни, C#, .NET, ASP.NET
ASP.NET MVC курс – HTML, SQL, C#, .NET, ASP.NET MVC
алго академия – състезателно програмиране, състезания
курс мобилни приложения с iPhone, Android, WP7, PhoneGap
Дончо Минков - сайт за програмиране
Николай Костов - блог за програмиране
C# курс, програмиране, безплатно
Free Trainings @ Telerik Academy
C# Programming @ Telerik Academy
Telerik Software Academy
academy.telerik.com
Telerik Academy @ Facebook
csharpfundamentals.telerik.com
facebook.com/TelerikAcademy
Telerik Software Academy Forums
forums.academy.telerik.com