Codementor Events

std Pro Tips for C++

Published Sep 04, 2017Last updated May 11, 2021
std Pro Tips for C++

Hi!

Another mentoring session, another time to sneak in some pro-tips. This time, it was all about the C++ Standard Library being really helpful.

Swapping things

If you have a need to swap things around in your code, please don't do this:

double temp = a;
a = b;
b = temp;

There's a super handy tool for the job:

std::swap(a,b);

It'll work for a lot of things, including containers and your own types (given some conditions), and it's actually really, really smart (for a nerdy example, it will utilize built-in CPU intrinsics to swap out primitive values in just a few micro-ops).

Updating minimums

In dynamic programming, there's often a need to implement a "running minimum/maximum" algorithm. In simple terms, that means taking values one after another and ending up with the smallest and biggest ones. That's one way to do that:

void update(int element) {
    if (element < minimum) {
        minimum = element;
    }
}

But three lines is three times more than it needs!

minimum = std::min(element, minimum);

This also works wonders when you have to create a third value out of two singles, e.g. some composition of two objects.

While we're on minimums...

... you've probably seen code that did this:

int minimum = 9999999;
int maximum = -9999999;

That's lousy! Setting aside weird magic numbers, there are bigger numbers than 9999999 that'll fit in an int. Standard library comes to the rescue again:

#include <limits>
int minimum = std::numeric_limits<int>::max();
int maximum = std::numeric_limits<int>::min();

There's also a catch there — this won't work properly for double. To get the real smallest negative double, you'd need to use std::numeric_limits<double>::lowest() instead. However, IEEE754 floating point numbers have values even smaller (bigger) than that! Specifically, a float/double that will compare smaller/greater to every other value can be obtained by std::numeric_limits<double>::infinity() (add a minus sign in front for the minus-infinity), which is probably the best way to initialize values for such an algorithm.

Hope that was helpful!

Cover photo credit: Tech Daily

Discover and read more posts from Bartek Banachewicz
get started
post comments1Reply
Eric Horng
7 years ago

Nice! Very useful tips, I’ll definitely be using these in my own programming as well.