C++11 tricks- Codeforces
C++11 tricks- Codeforces
- Codeforces
|
GuyNEN | Logout
You have +393! Wow!
HOME TOP CATALOG CONTESTS GYM PROBLEMSET GROUPS RATING EDU API CALENDAR HELP
Before contest
C++11 for programming contests... Codeforces Round #845 (Div. 2)
6 days
By mukel, 9 years ago,
Updated: 30 December 2013 3:27 CEST (Added a brief introduction to Lambda Functions). → GuyNEN
Rating: 393
The new C++ standard, also known as C++11 and also as C++0x is here, with some sugars Contribution: 0
for programming contest. I'll update this thread soon with new contents (and better Settings
structure). You can use C++11 on Topcoder, Codeforces, HackerRank ... This thread is based Blog
Teams GuyNEN
on my own experience, so you don't need to dig on the whole C++11 specification to find
Submissions
some useful feature you can use in programming contests. Favourites
Talks
Contests
The "auto" keyword:
Type inference is included in many modern programming languages, and C++ is not behind,
the "auto" keyword works like "var" in C#, it only tells the compiler to infer the type for us: → Top rated
So, # User Rating
1 Benq 3813
map< string, pair< int, int > > somyLongTypeName = map< string, pair<
int, int > >(); 2 tourist 3768
3 maroonrk 3570
Can be shortened to, with no impact on speed, since the type is inferred at compile time: 4 Radewoosh 3535
5 fantasy 3526
auto longTypeNamesAreHistory = map< string, pair< int, int > >();
6 Um_nik 3523
Of course that a typedef could do the same, but using auto is faster (to type). 6 jiangly 3523
8 orzdevinwang 3441
Personally I think that one of the best use of auto is when dealing with iterators, for example: 9 cnnfls_csy 3427
10 zh0ukangyang 3423
for (map< string, pair< int, int > >::iterator it = m.begin(); it !=
Countries | Cities | Organizations View all →
m.end(); ++it)
{
/* do something with it */ → Top contributors
} # User Contrib.
1 awoo 180
Becomes:
1 -is-this-fft- 180
https://codeforces.com/blog/entry/10124 1/13
16/01/2023, 01:09 C++11 for programming contests... - Codeforces
map< int, string > numeral = { tourist → Codeforces Round #844 (Div. 1 +
Div. 2)
{0, "zero"},
Cheaters_Hunter → One Cheater becomes
{1, "one"}, expert and Specialist at the same round !!
{2, "two"},
{3, "three"}, -is-this-fft- → [Tutorial] Collection of little
techniques
{4, "four"},
{5, "five"}, n0sk1ll → Editorial for Hello 2023
We can even modify the elements (note the &): POPtab → What does "Div. 1 + Div. 2,
based on VK Cup 2022 — Elimination
Round" means?
vector< int > numbers = {2, 3, 5, 7};
alittlemiddle → Help me pls
for (auto& x : numbers)
Rising-coder → Should I go back ?
x *= 2;
ChthollyNotaSeniorious → Polynomial Round
2022 (Div. 1 + Div. 2) Editorial
for (auto x : numbers)
cout << x << endl; Vedkribhu → Need Help CSES Graph
Problem: High Score
https://codeforces.com/blog/entry/10124 2/13
16/01/2023, 01:09 C++11 for programming contests... - Codeforces
// inclusive range
template<typename T> number_range<T> range(T b, T e) {return
number_range<T>(b, e);}
or
Nothing to worry about speed, is exactly the same when compiled with -O2 (tested on g++
4.8), which is logical since all the operations of the iterators are delegated to underlying type
T (int or long long). Until now, my experience tell me that the new range for loops are easier
to write/read without any speed penalty. Note that this is not so practical since we need to
implement our own iterator and range classes, but if we have a pre-written template, the
code becomes very clean and readable.
Another common example, (no more -> for (int i = 0; i < G[u].size(); ++i)... :
But we can go even further (with the help of lambdas) and implement binary search using the
well known lower_bound and upper_bound functions:
int findSqrt(int n) {
int lo = 0, hi = n;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (mid * mid <= n)
lo = mid + 1;
else
hi = mid - 1;
}
return lo - 1;
}
int findSqrt(int n) {
int lb = lower_bound(number_iterator<int>(0),
number_iterator<int>(n), 0,
[&] (int value, int /* ignored */ ) {
return value * value <= n;
}
);
https://codeforces.com/blog/entry/10124 3/13
16/01/2023, 01:09 C++11 for programming contests... - Codeforces
return lb - 1;
}
As you can see, no need to cast (or de-reference) the resulting iterator, we can also use long
long (not doubles obviously).
Initialization can be somehow particular, please refer to this for further details.
Lambda functions:
Before the new standard, C++ used functors, which are classes that simulates functions, still
functions were not 1st class constructs. The new standard introduced lambda functions (still
not 1st class citizens), and make the use of functions more pleasant than before. Let's see a
trivial example:
sort(order.begin(), order.end(),
[&] (const int& a, const& int b) -> bool {
return heights[a] < heights[b];
}
);
See also the binary search implemented using lower_bound in the "Range based for loops"
section.
The above is a quite common use case, but one may wonder why use a lambda instead of a
simple static function, the reason is quite simple, the cool part is that lambda functions can
capture other variables (by value or by reference, is even possible to specify which variables
to capture), allowing us to access to all visible variables in the scope. The old style functions
can only access global variables. The compiler can infer the return type in most cases. My
advice is to avoid recursive lambda functions. Lambdas are a huge advance, but definetely
not the same as in functional languages were functions are real 1st class constructs.
C++
https://codeforces.com/blog/entry/10124 4/13
16/01/2023, 01:09 C++11 for programming contests... - Codeforces
for_each(v.begin(), v.end(),
[&] (int x) {
cout << x << endl;
}
)
Scala
v foreach println
Move semantics:
What is it and how it works?
C++03 and previous standards had a serious penalty when returning non-pointer values, eg.
vector< int >, map< string, int >, string?... since the whole value should be deep-copied by
value, move semantics is an optimization that avoid the copy of the whole structure and
integrates flawlessly to existing code. To explain better how it works (without entering in
technical details) let's try with a concrete example, let's assume we are returning a vector<
int > , instead of copy the vector when returning, it just "moves" (with the help of some
additional construct) what we are returning, the "move" is achieved by copying only the
necesary internal "data" of the vector, which consist in a pointer and a integer (size), that way
the whole data is NOT copied, only the necessary to have. Note that "move" is different from
copy, it just "moves" cleverly what is really important, resulting in a considerable boost. So
you can safely return vectors, maps, strings with a no performance overhead in a more
natural way that using pointers which can be harder to code, debug ...
More is coming, lambdas, benchmarks, regex, new pseudo-random number generators, bye
bye rand() ...
8 years ago, # ^ | +3
Also 2014 ACM-ICPC World Finals will switch the default C++ to
gnu++0x (C++0x plus GNU extensions)
→ Reply
nakeep
→ Reply
https://codeforces.com/blog/entry/10124 5/13
16/01/2023, 01:09 C++11 for programming contests... - Codeforces
→ Reply
3 years ago, # ^ | -11
chaudhary_19
9 years ago, # | +2
Also, we can use "long" instead of "long long" on 64 bit systems. As far as I
know, it works on topcoder but not on codechef. Haven't tried it on codeforces
though.
xorfire → Reply
9 years ago, # ^ | +5
9 years ago, # ^ | 0
9 years ago, # ^ | +5
8 years ago, # ^ | 0
https://codeforces.com/blog/entry/10124 6/13
16/01/2023, 01:09 C++11 for programming contests... - Codeforces
8 years ago, # ^
← Rev. 2 | +8
9 years ago, # | +5
9 years ago, # ^ | +8
mukel
→ Reply
9 years ago, # | 0
Thanks for this nice post! Could you suggest any good books on C++11, or
tutorials on inheritance of STL's container/iterator,etc?
→ Reply
ka16
9 years ago, # | +3
Nice tutorial, I haven't seen the range trick before. BTW, Bjarne Stroustrup's
C++11 FAQ is also very helpful: http://www.stroustrup.com/C++11FAQ.html
→ Reply
andreyv
7 years ago, # ^ | 0
3 years ago, # ^ | 0
but what if we want to traverse from l to r,where l>r. then what can we
do?
→ Reply
Dhruv_Gheewala
3 years ago, # ^ | 0
one way is, we can add this line before return statement in
range(b,e) :
Dhruv_Gheewala
if(b>e)return number_range(-b,-e); we can use our variable by
adding minus before it.
like :
https://codeforces.com/blog/entry/10124 7/13
16/01/2023, 01:09 C++11 for programming contests... - Codeforces
9 years ago, # | 0
http://channel9.msdn.com/Events/GoingNative/2013/An-Effective-Cpp11-14-
Sampler
9 years ago, # | 0
9 years ago, # ^ | +8
#include<array>
#include<iostream>
using namespace std;
int main(){
array<array<int, 10>, 10> a;
for (int i = 0; i < a.size(); ++i)
a[i].fill(i);
for (int i = 1; i < a.size(); i += 2)
a[i].swap(a[i - 1]);
000golabi
cout << a << endl;
/* prints
1,1,1,1,1,1,1,1,1,1
,0,0,0,0,0,0,0,0,0,0
,3,3,3,3,3,3,3,3,3,3
,2,2,2,2,2,2,2,2,2,2
,5,5,5,5,5,5,5,5,5,5
,4,4,4,4,4,4,4,4,4,4
,7,7,7,7,7,7,7,7,7,7
,6,6,6,6,6,6,6,6,6,6
,9,9,9,9,9,9,9,9,9,9
,8,8,8,8,8,8,8,8,8,8 */
return 0;
}
4 years ago, # ^ | 0
Hi.
https://codeforces.com/blog/entry/10124 8/13
16/01/2023, 01:09 C++11 for programming contests... - Codeforces
Thanks.
→ Reply
4 years ago, # ^ | 0
MrDindows
4 years ago, # ^ | 0
4 years ago,←# ^2 |
Rev. 0
template<class T,
std::size_t N> struct
array;
9 years ago, # ^ | +1
7 years ago, # ^ | 0
https://codeforces.com/blog/entry/10124 9/13
16/01/2023, 01:09 C++11 for programming contests... - Codeforces
7 years ago, # ^ | 0
9 years ago, # ^ | -9
9 years ago, # ^ | 0
riadwaw Here, you cant get [4] of a[0] because its stay of 3
elements
→ Reply
9 years ago, # ^ | +8
8 years ago, # | +2
Codeforces offer two options that include some of C++11 but not all, these are
MS Visual C++2010 and C++0x. For example : MS Visual C++2010 fails in
compilation of STL initializer lists, and C++0x fails in compiling stol() and stoi()
functions
nakeep
→ Reply
https://codeforces.com/blog/entry/10124 10/13
16/01/2023, 01:09 C++11 for programming contests... - Codeforces
First, why you ever need an auto in the declaration of a variable? I meant,
sometimes it would be shorter without auto .
number_iterator(T _v = 0) : v(_v) {}
johnchen902
Third, lower_bound should not be used like this, when there is a good
partition_point :
int findSqrt(int n) {
int lb = partition_point(number_iterator<int>(0),
number_iterator<int>(n),
[&] (int value) { return value * value <= n;
});
return lb - 1;
}
8 years ago, # ^ | 0
8 years ago, # ^ | +3
https://codeforces.com/blog/entry/10124 11/13
16/01/2023, 01:09 C++11 for programming contests... - Codeforces
as what OP did.
→ Reply
7 years ago, # | 0
I suppose it to work everywhere but want to notice it's not valid random access
iterator because being random access iterator means to be forward iterator and
ForwardIterator has a requirement:
[&](){
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (whatever(i, j)) {
return;
}
Jacob
// more code
}
}
}();
→ Reply
7 years ago, # ^ | 0
I call it "goto" :). Of course many people consider goto as really bad,
but for this particular case I think it's "the way".
Swistakk → Reply
7 years ago, # | 0
return false;
https://codeforces.com/blog/entry/10124 12/13
16/01/2023, 01:09 C++11 for programming contests... - Codeforces
return false;
}
→ Reply
7 years ago, # | 0
map< string, pair< int, int > > somyLongTypeName = map< string,
pair< int, int > >(); // C++
map<string, pair<int, int>> somyLongTypeName = map<string,
cdkrot pair<int, int>>(); // C++11, much better!
→ Reply
Supported by
https://codeforces.com/blog/entry/10124 13/13