DEV Community

Wojciech Jedynak
Wojciech Jedynak

Posted on • Updated on

C++ for algorithms (part 1.)

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
Enter fullscreen mode Exit fullscreen mode

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());
Enter fullscreen mode Exit fullscreen mode

Tip #2: foreach loop

long sum = 0;
for (auto &d : v)
  sum += d;
Enter fullscreen mode Exit fullscreen mode

Tip #3: convert integer to string

Old C-style

#include <cstdlib>
//....
char buf[10];
int n = 123;
sprintf(buf, "%d", n);
Enter fullscreen mode Exit fullscreen mode

C++ style

string s = to_string(34);
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

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; 
  }
};
Enter fullscreen mode Exit fullscreen mode

Easy problems to practice

  1. Find biggest number
  2. Find sum
  3. Print comma separated
  4. Find index of 1

Top comments (0)