vector<>
template#include <vector>
.push_back()
member function resizes the vector and appends the additional element to the end..resize(int)
if you know the size of the vector ahead of time, then to add all elements.vector<>
overloads operator[]()
, so indexing can be done like an array..at()
function can be used.for (size_t i = 0; i < values.size(); ++i) {
cout << values[i] << endl;
}
#include <stack>
stack<int> values;
T top();
. This returns the value on the top of the stack.#include <queue>
queue<int> values;
T front();
void push(elem);
void pop();
bool empty();
A deque, pronounced "deck", is a double-ended queue. Instead of being restricted to pushing and popping from a single end, you can use both ends.
stack
and queue
are actually implemented with a deque!void push_front(elem);
T front();
void pop_front();
void push_back(elem);
T back();
void pop_back();
bool empty();
C++ cout
is slow, because endl
causes the buffer to flush. This delegates it to the OS, so it's slower.
Faster options:
'\n'
, stringstream
s to print everything all at once#ifdef NDEBUG
ios_base::sync_with_stdio(false);
#endif
Make sure to use the -DNDEBUG
flag on compilation, though. It helps to put this in a makefile for release builds only.
There are typically many different algorithms to accomplish the same task, but some are definitely better than others. Complexity analysis is a way to sift out the bad stuff.
In order from most important to least important:
-g
flag adds annotations to your files and should only be used for debugging. The -O3
flag turns on the highest level of optimization.int
s and double
s correctly? Machines vary in the amount of memory they allocate for data types).Let's say you have a graph \(G = \left
Steps in a program are considered to be single expressions. These include:
And many more.
Here is a walkthrough of a basic step counting exercise:
int sum = 0; // init: 1
for (int i = 0; i < n; ++i) { // init: 1, test: n, update: n, test fail: 1
sum += i; // 1*n
}
return sum; // 1
Therefore, the sum of steps is \(4 + 3n\). Note that loops generally take \(2n + 2\) steps.
\(f(n) = O(g(n))\) iff there exist constants \(c > 0\) and \(n_0 > 0\) such that:
whenever \(n > n_0\).
This is a sufficient, but not necessary condition:
For example, is \(\log_2(n) = O(2n)\)?
Yes.
Remember that you can drop constants in front of either \(f(n)\) or \(g(n)\) and not have anything change. Therefore, \(3n^2 = O(5n^2) = O(15n^2)\).