[go: up one dir, main page]

0% found this document useful (0 votes)
23K views51 pages

C++ Tips and Tricks (Bruce Merry)

The document discusses various C++ tips and tricks organized into sections on portable tips, GCC tips, and traps. It covers topics such as assertions, string conversions, references, and undefined behavior. The tips are presented by Bruce Merry at an IOI training event.

Uploaded by

xilvenkat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23K views51 pages

C++ Tips and Tricks (Bruce Merry)

The document discusses various C++ tips and tricks organized into sections on portable tips, GCC tips, and traps. It covers topics such as assertions, string conversions, references, and undefined behavior. The tips are presented by Bruce Merry at an IOI training event.

Uploaded by

xilvenkat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

C++ tips and

tricks
Bruce Merry

Portable tips
Assertions
String Conversions
References
Typedefs
C++ tips and tricks
I/O performance

GCC tips
Compilation flags
Header files Bruce Merry
Traps
Undefined Behaviour
Surprising Behaviour

IOI Training Dec 2013


Outline

C++ tips and


tricks
Bruce Merry 1 Portable tips
Assertions
Portable tips
Assertions String Conversions
String Conversions
References References
Typedefs
I/O performance Typedefs
GCC tips I/O performance
Compilation flags
Header files

Traps
2 GCC tips
Undefined Behaviour
Surprising Behaviour
Compilation flags
Header files

3 Traps
Undefined Behaviour
Surprising Behaviour
Outline

C++ tips and


tricks
Bruce Merry 1 Portable tips
Assertions
Portable tips
Assertions String Conversions
String Conversions
References References
Typedefs
I/O performance Typedefs
GCC tips I/O performance
Compilation flags
Header files

Traps
2 GCC tips
Undefined Behaviour
Surprising Behaviour
Compilation flags
Header files

3 Traps
Undefined Behaviour
Surprising Behaviour
Assertions

C++ tips and


tricks
Bruce Merry
You can check that something is true using assert:
Portable tips
Assertions
String Conversions #include <cassert>
References
Typedefs int main()
I/O performance
{
GCC tips
Compilation flags assert(1 == 2);
Header files
}
Traps
Undefined Behaviour
Surprising Behaviour Output:

test_assert: test_assert.cpp:4: int main():


Assertion ‘1 == 2’ failed.
Disabling Assertions

C++ tips and


tricks
Bruce Merry

Portable tips
Assertions
String Conversions
References
Typedefs
I/O performance
To disable assertions, add
GCC tips
Compilation flags
#define NDEBUG
Header files

Traps as the first line of your source.


Undefined Behaviour
Surprising Behaviour
Caution

C++ tips and


tricks
Bruce Merry #define NDEBUG
#include <cassert>
Portable tips
Assertions #include <iostream>
String Conversions
References using namespace std;
Typedefs
I/O performance bool foo() {
GCC tips cout << "In foo\n";
Compilation flags
Header files return true;
Traps }
Undefined Behaviour
Surprising Behaviour

int main() {
assert(foo());
}
Caution

C++ tips and


tricks
Bruce Merry #define NDEBUG
#include <cassert>
Portable tips
Assertions #include <iostream>
String Conversions
References using namespace std;
Typedefs
I/O performance bool foo() {
GCC tips cout << "In foo\n";
Compilation flags
Header files return true;
Traps }
Undefined Behaviour
Surprising Behaviour

int main() {
assert(foo());
}
When assertions are disabled, the expression is not
evaluated.
Outline

C++ tips and


tricks
Bruce Merry 1 Portable tips
Assertions
Portable tips
Assertions String Conversions
String Conversions
References References
Typedefs
I/O performance Typedefs
GCC tips I/O performance
Compilation flags
Header files

Traps
2 GCC tips
Undefined Behaviour
Surprising Behaviour
Compilation flags
Header files

3 Traps
Undefined Behaviour
Surprising Behaviour
String-To-Integer Conversions

C++ tips and


tricks
Bruce Merry

Portable tips
Assertions
String Conversions Use istringstream to treat a string as an input stream:
References
Typedefs
I/O performance #include <sstream>
GCC tips int x;
Compilation flags
Header files istringstream stream("123");
Traps
Undefined Behaviour
stream >> x;
Surprising Behaviour // Now x == 123
String-To-Integer Conversions

C++ tips and


tricks
Bruce Merry

Portable tips
Assertions
String Conversions You can reduce typing by using a C function instead:
References
Typedefs
I/O performance #include <cstdlib>
GCC tips string xstr = "123";
Compilation flags
Header files string ystr = "12345678912345678";
Traps
Undefined Behaviour
int x = atoi(xstr.c_str());
Surprising Behaviour long long y = atoll(ystr.c_str());
String-To-Integer Conversions

C++ tips and


tricks
Bruce Merry

Portable tips
Assertions
String Conversions C++11 has a more convenient wrapper:
References
Typedefs
I/O performance #include <string>
GCC tips string xstr = "123";
Compilation flags
Header files string ystr = "12345678912345678";
Traps
Undefined Behaviour
int x = stoi(xstr);
Surprising Behaviour long long y = stoll(ystr);
Integer-To-String Conversions

C++ tips and


tricks
Bruce Merry

Portable tips
Assertions
String Conversions The general solution is ostringstream:
References
Typedefs
I/O performance #include <sstream>
GCC tips ostringstream o;
Compilation flags
Header files o << 123;
Traps
Undefined Behaviour
string s = o.str();
Surprising Behaviour // s == "123"
Integer-To-String Conversions

C++ tips and


tricks
Bruce Merry

Portable tips
Assertions
String Conversions
References
Typedefs
I/O performance
C++11 again has a convenience wrapper
GCC tips
Compilation flags
#include <string>
Header files
string s = to_string(123);
Traps
Undefined Behaviour
Surprising Behaviour
Outline

C++ tips and


tricks
Bruce Merry 1 Portable tips
Assertions
Portable tips
Assertions String Conversions
String Conversions
References References
Typedefs
I/O performance Typedefs
GCC tips I/O performance
Compilation flags
Header files

Traps
2 GCC tips
Undefined Behaviour
Surprising Behaviour
Compilation flags
Header files

3 Traps
Undefined Behaviour
Surprising Behaviour
Introduction

C++ tips and


tricks
Bruce Merry

Portable tips
Assertions
String Conversions
References
Typedefs In Java and Python, all objects are references:
I/O performance

GCC tips
Passing to a function is cheap: just another reference
Compilation flags
Header files Callee function can modify the object
Traps
Undefined Behaviour
Every object must be explicitly created (e.g., with new)
Surprising Behaviour
C++ Default

C++ tips and


tricks
Bruce Merry

Portable tips
Assertions
By default, C++ objects are values:
String Conversions
References
Typedefs
I/O performance

GCC tips
Compilation flags
Header files

Traps
Undefined Behaviour
Surprising Behaviour
C++ Default

C++ tips and


tricks
Bruce Merry

Portable tips
Assertions
By default, C++ objects are values:
String Conversions
References
Typedefs
void foo(vector<string> grid)
I/O performance
{
GCC tips
Compilation flags
// foo operates on a *copy* of grid
Header files
}
Traps
Undefined Behaviour
Surprising Behaviour
C++ Default

C++ tips and


tricks
Bruce Merry

Portable tips
Assertions
By default, C++ objects are values:
String Conversions
References
Typedefs
void foo(vector<string> grid)
I/O performance
{
GCC tips
Compilation flags
// foo operates on a *copy* of grid
Header files
}
Traps
Undefined Behaviour
Surprising Behaviour
string mystrings[4];
// array contains 4 empty strings
Reference arguments

C++ tips and


tricks
Bruce Merry
To make a parameter a reference, prefix it with &:
Portable tips
Assertions void foo(vector<string> &grid)
String Conversions
References {
Typedefs
I/O performance // foo now operates on the original grid
GCC tips }
Compilation flags
Header files

Traps
Undefined Behaviour
Surprising Behaviour
Reference arguments

C++ tips and


tricks
Bruce Merry
To make a parameter a reference, prefix it with &:
Portable tips
Assertions void foo(vector<string> &grid)
String Conversions
References {
Typedefs
I/O performance // foo now operates on the original grid
GCC tips }
Compilation flags
Header files

Traps
Can also qualify references as const:
Undefined Behaviour
Surprising Behaviour void foo(const vector<string> &grid)
{
// foo is prevented from modifying grid
}
Reference Variables

C++ tips and


tricks
Bruce Merry

Portable tips
Assertions
Variables can be references, but they cannot be changed:
String Conversions
References
Typedefs
vector<string> strings(5);
I/O performance
string &first = strings[0];
GCC tips
Compilation flags
string &second = strings[1];
Header files
string &something; // error
Traps
Undefined Behaviour
first += "hello"; // appends to strings[0]
Surprising Behaviour
// copy one *string* to another:
second = first;
Pointers

C++ tips and


tricks
Bruce Merry

Portable tips
Assertions
String Conversions
References Pointers are similar to references
Typedefs
I/O performance
Can be changed to point at other things
GCC tips
Compilation flags Can be null pointers
Header files

Traps Syntax is more roundabout


Undefined Behaviour
Surprising Behaviour Avoid them for now
Outline

C++ tips and


tricks
Bruce Merry 1 Portable tips
Assertions
Portable tips
Assertions String Conversions
String Conversions
References References
Typedefs
I/O performance Typedefs
GCC tips I/O performance
Compilation flags
Header files

Traps
2 GCC tips
Undefined Behaviour
Surprising Behaviour
Compilation flags
Header files

3 Traps
Undefined Behaviour
Surprising Behaviour
Typedefs

C++ tips and


tricks
Bruce Merry

Portable tips
Assertions
String Conversions Can define shorthand for other types:
References
Typedefs
I/O performance typedef long long ll;
GCC tips typedef vector<vector<ll> > vvll;
Compilation flags
Header files ...
Traps
Undefined Behaviour
// declare a vector<vector<long long> >:
Surprising Behaviour vvll myarray;
Outline

C++ tips and


tricks
Bruce Merry 1 Portable tips
Assertions
Portable tips
Assertions String Conversions
String Conversions
References References
Typedefs
I/O performance Typedefs
GCC tips I/O performance
Compilation flags
Header files

Traps
2 GCC tips
Undefined Behaviour
Surprising Behaviour
Compilation flags
Header files

3 Traps
Undefined Behaviour
Surprising Behaviour
Improving Read Performance

C++ tips and


tricks
Bruce Merry
Add ios::sync_with_stdio(false) to the start of your
Portable tips
Assertions
program to improve cin performance.
String Conversions
References
Typedefs
I/O performance Table : Input performance (time to read 107 integers)
GCC tips
Compilation flags
Header files Method Time (s)
Traps
Undefined Behaviour cin 2.70
Surprising Behaviour
cin with tweak 0.78
scanf 0.84
Improving Read Performance

C++ tips and


tricks
Bruce Merry
Add ios::sync_with_stdio(false) to the start of your
Portable tips
Assertions
program to improve cin performance.
String Conversions
References
Typedefs
I/O performance Table : Input performance (time to read 107 integers)
GCC tips
Compilation flags
Header files Method Time (s)
Traps
Undefined Behaviour cin 2.70
Surprising Behaviour
cin with tweak 0.78
scanf 0.84

Side effect: do not mix cin and scanf


Improving Write Performance

C++ tips and


tricks
Bruce Merry
What is the difference between these two lines?

Portable tips
cout << 123 << endl;
Assertions
String Conversions
cout << 123 << ’\n’;
References
Typedefs
I/O performance

GCC tips
Compilation flags
Header files

Traps
Undefined Behaviour
Surprising Behaviour
Improving Write Performance

C++ tips and


tricks
Bruce Merry
What is the difference between these two lines?

Portable tips
cout << 123 << endl;
Assertions
String Conversions
cout << 123 << ’\n’;
References
Typedefs
I/O performance
Using endl flushes the output.
GCC tips
Compilation flags
Header files

Traps
Undefined Behaviour
Surprising Behaviour
Improving Write Performance

C++ tips and


tricks
Bruce Merry
What is the difference between these two lines?

Portable tips
cout << 123 << endl;
Assertions
String Conversions
cout << 123 << ’\n’;
References
Typedefs
I/O performance
Using endl flushes the output.
GCC tips
Compilation flags
Header files Table : Output performance (time to write 107 integers)
Traps
Undefined Behaviour
Surprising Behaviour Method Time (s)
endl 2.34
’\n’ 0.75
printf 0.80
Outline

C++ tips and


tricks
Bruce Merry 1 Portable tips
Assertions
Portable tips
Assertions String Conversions
String Conversions
References References
Typedefs
I/O performance Typedefs
GCC tips I/O performance
Compilation flags
Header files

Traps
2 GCC tips
Undefined Behaviour
Surprising Behaviour
Compilation flags
Header files

3 Traps
Undefined Behaviour
Surprising Behaviour
Warnings

C++ tips and


tricks
Bruce Merry

Portable tips
Assertions
String Conversions
References
Typedefs
I/O performance

GCC tips
-Wall Provide lots of helpful warnings
Compilation flags
Header files
-W Provide even more warnings, some useless
Traps
Undefined Behaviour
Surprising Behaviour
Optimisation

C++ tips and


tricks
Bruce Merry

Portable tips
Assertions
String Conversions Use -O2 to optimize your code
References
Typedefs
I/O performance
Speedup varies a lot, depending on code
GCC tips
Compilation flags
Header files

Traps
Undefined Behaviour
Surprising Behaviour
Optimisation

C++ tips and


tricks
Bruce Merry

Portable tips
Assertions
String Conversions Use -O2 to optimize your code
References
Typedefs
I/O performance
Speedup varies a lot, depending on code
GCC tips Interferes with debugging tools
Compilation flags
Header files

Traps
Undefined Behaviour
Surprising Behaviour
Optimisation

C++ tips and


tricks
Bruce Merry

Portable tips
Assertions
String Conversions Use -O2 to optimize your code
References
Typedefs
I/O performance
Speedup varies a lot, depending on code
GCC tips Interferes with debugging tools
Compilation flags
Header files Undefined behaviour can change
Traps
Undefined Behaviour
Surprising Behaviour
Optimisation

C++ tips and


tricks
Bruce Merry

Portable tips
Assertions
String Conversions Use -O2 to optimize your code
References
Typedefs
I/O performance
Speedup varies a lot, depending on code
GCC tips Interferes with debugging tools
Compilation flags
Header files Undefined behaviour can change
Traps
Undefined Behaviour Some warnings only work with optimisation
Surprising Behaviour
Optimisation

C++ tips and


tricks
Bruce Merry

Portable tips
Assertions
String Conversions Use -O2 to optimize your code
References
Typedefs
I/O performance
Speedup varies a lot, depending on code
GCC tips Interferes with debugging tools
Compilation flags
Header files Undefined behaviour can change
Traps
Undefined Behaviour Some warnings only work with optimisation
Surprising Behaviour

Can also do -O3, but has diminishing returns


Outline

C++ tips and


tricks
Bruce Merry 1 Portable tips
Assertions
Portable tips
Assertions String Conversions
String Conversions
References References
Typedefs
I/O performance Typedefs
GCC tips I/O performance
Compilation flags
Header files

Traps
2 GCC tips
Undefined Behaviour
Surprising Behaviour
Compilation flags
Header files

3 Traps
Undefined Behaviour
Surprising Behaviour
Including The Standard Libraries

C++ tips and


tricks
Bruce Merry

Portable tips
Assertions
String Conversions
References
Typedefs
I/O performance
This will pull in all the standard library headers
GCC tips
Compilation flags
#include <bits/stdc++.h>
Header files

Traps It does make compilation quite slow.


Undefined Behaviour
Surprising Behaviour
Outline

C++ tips and


tricks
Bruce Merry 1 Portable tips
Assertions
Portable tips
Assertions String Conversions
String Conversions
References References
Typedefs
I/O performance Typedefs
GCC tips I/O performance
Compilation flags
Header files

Traps
2 GCC tips
Undefined Behaviour
Surprising Behaviour
Compilation flags
Header files

3 Traps
Undefined Behaviour
Surprising Behaviour
Uninitialized Data

C++ tips and


tricks
Bruce Merry

Portable tips
Assertions
String Conversions
References
Typedefs int x;
I/O performance

GCC tips
int y[3];
Compilation flags vector<int> z(4);
Header files

Traps
cout << x << ’ ’ << y[1] << ’ ’ << z[2];
Undefined Behaviour
Surprising Behaviour Which values are well-defined?
Uninitialized Data

C++ tips and


tricks
Bruce Merry

Portable tips The following are generally safe:


Assertions
String Conversions
References
Classes with a constructor, if the constructor explicitly
Typedefs
I/O performance
initialises all fields.
GCC tips STL containers like vector (even for primitive types)
Compilation flags
Header files
Primitive types are undefined when:
Traps
Undefined Behaviour Declared directly
Surprising Behaviour

Declared in an array
Declared in a struct/class and not set by constructor
Out-of-range Array Access

C++ tips and


tricks
Bruce Merry

Portable tips
Assertions
String Conversions
References
Typedefs
I/O performance
int x[3] = {1, 2, 3};
GCC tips
Compilation flags
x[3] = 4;
Header files

Traps Anything can happen here!


Undefined Behaviour
Surprising Behaviour
References to Local Variables

C++ tips and


tricks
Bruce Merry

Portable tips Do not try to return containers by reference:


Assertions
String Conversions
References
vector<int> &foo(int n)
Typedefs
I/O performance
{
GCC tips vector<int> ans;
Compilation flags
Header files for (int i = 0; i < n; i++)
Traps ans.push_back(i);
Undefined Behaviour
Surprising Behaviour return ans;
}
References to Local Variables

C++ tips and


tricks
Bruce Merry

Portable tips Do not try to return containers by reference:


Assertions
String Conversions
References
vector<int> &foo(int n)
Typedefs
I/O performance
{
GCC tips vector<int> ans;
Compilation flags
Header files for (int i = 0; i < n; i++)
Traps ans.push_back(i);
Undefined Behaviour
Surprising Behaviour return ans;
}
Return by value
References to Local Variables

C++ tips and


tricks
Bruce Merry

Portable tips Do not try to return containers by reference:


Assertions
String Conversions
References
vector<int> &foo(int n)
Typedefs
I/O performance
{
GCC tips vector<int> ans;
Compilation flags
Header files for (int i = 0; i < n; i++)
Traps ans.push_back(i);
Undefined Behaviour
Surprising Behaviour return ans;
}
Return by value — GCC will optimise it
Outline

C++ tips and


tricks
Bruce Merry 1 Portable tips
Assertions
Portable tips
Assertions String Conversions
String Conversions
References References
Typedefs
I/O performance Typedefs
GCC tips I/O performance
Compilation flags
Header files

Traps
2 GCC tips
Undefined Behaviour
Surprising Behaviour
Compilation flags
Header files

3 Traps
Undefined Behaviour
Surprising Behaviour
Mod on Negative Values

C++ tips and


tricks
Bruce Merry

Portable tips
Assertions
String Conversions 5 % 3 == 2
References
Typedefs
I/O performance
-5 % 3 == -2 (unlike Python)
GCC tips
Compilation flags
When a problem asks for an answer modulo M:
Header files

Traps ans %= M;
Undefined Behaviour
Surprising Behaviour
if (ans < 0)
ans += M;
Unsigned Is Evil

C++ tips and


tricks
Bruce Merry

Portable tips
Assertions
String Conversions What is wrong with this code?
References
Typedefs
I/O performance // One pass of bubblesort
GCC tips
Compilation flags
for (int i = 0; i < arr.size() - 1; i++)
Header files if (arr[i] > arr[i + 1])
Traps swap(arr[i], arr[i + 1]);
Undefined Behaviour
Surprising Behaviour
Unsigned Is Evil

C++ tips and


tricks
Bruce Merry

Portable tips
Assertions
String Conversions What is wrong with this code?
References
Typedefs
I/O performance // One pass of bubblesort
GCC tips
Compilation flags
for (int i = 0; i < arr.size() - 1; i++)
Header files if (arr[i] > arr[i + 1])
Traps swap(arr[i], arr[i + 1]);
Undefined Behaviour
Surprising Behaviour

If arr is empty, then arr.size() - 1 wraps around.


Stack Overflow

C++ tips and


tricks
Bruce Merry

Portable tips
Assertions
String Conversions
References
Typedefs
I/O performance
Function parameters and local variables kept on a stack
GCC tips Stack size limits possible recursion depth
Compilation flags
Header files
Linux defaults to an 8 MiB stack!
Traps
Undefined Behaviour
Surprising Behaviour
So be careful with more than 100 000 levels of recursion.

You might also like