What is the point of STL Character Traits?

Character traits are an extremely important component of the streams and strings libraries because they allow the stream/string classes to separate out the logic of what characters are being stored from the logic of what manipulations should be performed on those characters. To begin with, the default character traits class, char_traits<T>, is used extensively in … Read more

How to efficiently get a `string_view` for a substring of `std::string`

There’s the free-function route, but unless you also provide overloads for std::string it’s a snake-pit. #include <string> #include <string_view> std::string_view sub_string( std::string_view s, std::size_t p, std::size_t n = std::string_view::npos) { return s.substr(p, n); } int main() { using namespace std::literals; auto source = “foobar”s; // this is fine and elegant… auto bar = sub_string(source, 3); … Read more

How to get the number of characters in a std::string?

If you’re using a std::string, call length(): std::string str = “hello”; std::cout << str << “:” << str.length(); // Outputs “hello:5” If you’re using a c-string, call strlen(). const char *str = “hello”; std::cout << str << “:” << strlen(str); // Outputs “hello:5” Or, if you happen to like using Pascal-style strings (or f***** strings … Read more

Legality of COW std::string implementation in C++11

It’s not allowed, because as per the standard 21.4.1 p6, invalidation of iterators/references is only allowed for — as an argument to any standard library function taking a reference to non-const basic_string as an argument. — Calling non-const member functions, except operator[], at, front, back, begin, rbegin, end, and rend. For a COW string, calling … Read more

How to trim an std::string?

EDIT Since c++17, some parts of the standard library were removed. Fortunately, starting with c++11, we have lambdas which are a superior solution. #include <algorithm> #include <cctype> #include <locale> // trim from start (in place) static inline void ltrim(std::string &s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](unsigned char ch) { return !std::isspace(ch); })); } // trim from … Read more