What is the difference between using a struct with two fields and a pair?

std::pair provides pre-written constructors and comparison operators. This also allows them to be stored in containers like std::map without you needing to write, for example, the copy constructor or strict weak ordering via operator < (such as required by std::map). If you don’t write them you can’t make a mistake (remember how strict weak ordering … Read more

Can we rely on the reduce-capacity trick?

I’ve always been taught that there is no guaranteed standard way to lower the capacity. All methods have been (and still are) implementation defined. § 23.2.1\8 says: The expression a.swap(b), for containers a and b of a standard container type other than array, shall exchange the values of a and b without invoking any move, … Read more

How to truncate a file while it is open with fstream

I don’t think you can get “atomic” operation but using the Filesystem Technical Specification that has now been accepted as part of the Standard Library (C++17) you can resize the file like this: #include <fstream> #include <sstream> #include <iostream> #include <experimental/filesystem> // compilers that support the TS // #include <filesystem> // C++17 compilers // for … Read more