Introduction
I haven't been using C++ for a while, so I'm writing some notes while I solve some algorithm challenges.
Tip #0: Create a vector
vector<int> v; // empty vector
vector<int> v(n); // vector of size n - can be dynamic
vector<int> v(n, 42) // initialize all n-elements to 42
vector<int> v{0, 1, 2, 42}; // 4 elements like in the list
Tip #1: Find the biggest (smallest) element in vector
#include <algorithm>
//....
auto biggest = *max_element(v.start(), v.end());
auto smallest = *min_element(v.start(), v.end());
Tip #2: foreach loop
long sum = 0;
for (auto &d : v)
sum += d;
Tip #3: convert integer to string
Old C-style
#include <cstdlib>
//....
char buf[10];
int n = 123;
sprintf(buf, "%d", n);
C++ style
string s = to_string(34);
Tip #4: find element in vector
#include <algorithm>
int value = 42;
auto iterator = find(v.begin(), v.end(), value);
// if not found, iterator == v.end()
auto index = iterator - v.begin();
Tip #5: make a struct sortable
struct Edge {
int start;
int end;
int cost;
bool operator<(const Edge &other) const {
return this->cost < other.cost;
}
};
Top comments (0)