The little functions that matter

Starting with C++20, some very useful functions for searching have been added to some standard containers, such as std::map, std::set, and std::string. These have been required for a long time and it’s good to see that the committee finally agreed upon their value. I hope this is the beginning of some wonderful additions.

Maps and sets

A typical operation when working with maps is to check if a given key exists. How do you do this in C++17? Well, it’s simple:

Although it may be simple it’s not user-friendly at all. For this reason, many have written their own contains() function that takes a map and a key and returns a boolean indicating whether the map contains the key. This is no longer necessarily in C++20 where std::map has a contains() method.

The same is true for std::set too.

In fact, a contains() function has been added to the following types in C++20:

Strings

A similar problem concerns strings. Often, we need to know if a string contains another string. This is how you do it in C++17:

A particular case related to strings is finding a substring at the beginning and end of the string. Searching at the beginning is relatively simple:

But searching at the end requires a helper function. A possible implementation is this:

Which can be used as follows:

(Note: You can find alternative implementations for such a function here.)

This have been greatly simplified in C++20 where std::basic_string and std::basic_string_view have two more methods: starts_with() and ends_with().

However, there is a huge miss in C++20: a function for checking if a string contains a substring. Now, during the last C++ ISO committee meeting, such a method has been added to C++23 (P1679). This will enable us to write the following:

And that is how we always wanted to write code.
Thank you!

But…

You should keep in mind that these new string functions are case sensitive. They do not take a predicate to allow you to customize the way the search is done. Therefore, if you need to perform case-insensitive searching, then you still need to implement that yourself. A possible implementation for contains(), starts_with(), and ends_with() that performs case-insensitive search is shown here:

And these can be used as follows:

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.