3011.io

C++

Various snippets of code to get things done in C++. Note that most of these are nowhere near production quality. The intent is to copy them into a debug build to set things up quickly. Use this at your own risk.

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()
        : mStart(Clock::now())
    {}

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

private:
    TimePoint mStart;
};

Numbers from strings

Somewhat better than trying to use std::stoi and friends.

template <typename T>
T Parse(std::string_view input)
{
    T result {};
    const char *begin = input.data();
    const char *end = input.data() + input.size();
    auto [ptr, ec] = std::from_chars(begin, end, result);
    if (ec != std::errc() || ptr != end) {
        // Note(3011): Serious code would have better error reporting.
        throw std::runtime_error("Could not parse");
    }
    return result;
}