3011.io

C++ Snippets

This is a collection of various small pieces of code I find useful occasionally.

File to std::string

A simple function to get a whole file into a std::string in a few lines. Note that this requires <string>, <fstream>, and <iterator>. Also, do not use this in places where you care about performance, the iterators are quite slow.

std::string ReadFile(const std::string &name)
{
    std::ifstream file(name);
    if (!file) {
        return "";
    }
    return std::string(
        (std::istreambuf_iterator<char>(file)),
         std::istreambuf_iterator<char>()
    );
}

Stopwatches, and measuring time

A basic stopwatch, measures a single scope. Enough for getting a rough idea of how long something takes.

class Stopwatch
{
public:
    using Clock = std::chrono::steady_clock;
    using TimePoint = Clock::time_point;
    using Duration = Clock::duration;

    Stopwatch()
        : Start(Clock::now())
    {}

    ~Stopwatch()
    {
        using std::chrono::duration_cast;
        TimePoint end = Clock::now();
        Duration elapsed = end - Start;
        auto microseconds = duration_cast<std::chrono::microseconds>(elapsed).count();
        std::println("Stopwatch measured {:.3f}ms", microseconds / 1000.0);
    }

private:
    TimePoint Start;
};