Category Archives: STL

Standard Template Library

Three Ways to Find Files

Let’ say we have to implement a function that search a folder to recursively find files having an extension from a given list of extensions. This article shows three possible implementations: one using FindFirstFile and FindNextFile WinAPI functions, one using CFileFind MFC class and one using Filesystem Library.

Find files using FindFirstFile and FindNextFile WinAPI functions

Althugh this implementation uses some ATL stuff to make things easier, it appears still quite complicated.

Find files using CFileFind MFC class

Using CFileFind MFC class can make code a little bit shorter and the programmer’s life easier.

Note: IsStringInListNoCase searches a list for a string, not case sensitive. You can find its implementation in the attached demo solution.

Find files using Filesystem Library

Here it is:

Hurray, we did it in just few lines of code! :)
Of course, it can be used in MFC, ATL, Win32 and Console applications, as well.

Demo solution

The demo solution contains three projects, each having one of the above implementations.
Download: Find Files Samples (Visual Studio 2015).zip (51)

Resources and related articles

Using Lambdas in MFC Applications – Part 1: Sorting Arrays

Beginning with Visual Studio 2010 which supports lambda expressions introduced by C++11 standard, you can handily sort an MFC array like in the following example:

Sorting CStringArray by using a lambda expression

Of course, you can write similar code for other types of MFC arrays like CArray, CUIntArray, and so on.
But also you can easily write a kind of “generic lambda” in order to sort any type of MFC arrays.

Using decltype to sort any type of MFC array

That’s pretty cool… However would be nice to be possible to get rid of “wordy” constructions like “decltype(*arr.GetData())” in the lambda’s formal parameters list. Good news! There is a proposal for next C++ standards: using auto type-specifier in order to make generic lambda expressions (which accept any type of arguments). And that is already supported in Visual Studio 2015.

Using generic (polymorphic) lambda expressions

Notes

  • Some people may claim that using MFC collection classes is obsolete and must use STL containers instead. That’s an old subject of arguing but it’s not in scope of this short article.
    It simply presents how to sort MFC arrays by using lambda expressions.

References and related articles

C++11: Let’s Write a “Hello Lambda!”

A lambda expression (aka lambda function), introduced in C++11 standard, is a simplified notation for defining an anonymous function object. However, its syntax and using may look weird for many people so let’s try to make a simple program to accommodate with it.

Let’s describe each part, in order.

The parts of a lambda expression

  • [] is the lambda introducer that may be empty or may contain a capture list; this part is mandatory for defining a lambda expression;
  • () is a formal parameters list; if it takes no parameters and no specifier like mutable or noexcept has been used, this part is optional;
  • mutable is an optional specifier which indicates that the copies of variables captured by value can be modified inside the lambda body;
  • throw() (or noexcept) is an exception specifier which is also optional;
  • ->void is the return type; it is optional if the compiler can deduce the return type;
  • { std::cout << "Hello Lambda!"; } is the body specifying the code to be executed.
  • finally, we have in our example a function-call operator, (), which is not a part of lambda expression.

Getting rid of optional parts, we can make our program simpler, as follows:

Further, let’s take a little deeper look in the lambda introducer part.

The lambda introducer and the capture list

As already said before, the lambda introducer that may be empty or may contain a capture list. An empty lambda introducer means “no capture is made”. Otherwise, the local variables from the place where lambda is defined can be “captured” (i.e. used in the lambda body) as follows:

  • [=] all local variables are implicitly accessed by value;
  • [&] all local variables are implicitly accessed by reference;
  • [capture_list] a list of variable names to be captured (explicit capture); if a variable name is preceded by & then it is captured by reference; otherwise, it is captured by value;
  • [=, capture_list] all variables which are not in the capture_list are captured by value;
  • [&, capture_list] all variables which are not in the capture_list are captured by reference;

Note that variables captured by value cannot be modified inside the lambda body, except case the mutable specifier has been used.
Now, let’s make our program a little bit more complicated to illustrate the using of capture list and other lambda expression parts.

Notes

  • This article presented just trivial examples, introducing lambda expressions as simple as possible. You can find tens of articles and examples presenting lambdas deeper. See also references and related articles, below.
  • std::function is an STL class that wraps callable objects like functions, lambda expressions and so on.

References and related articles

User defined literals

The C++ language defines various built-in literals (numerical, character, string, boolean and pointer) and a series of prefixes and suffixes to specify some of them. The suffix or prefix is part of the literal.

The C++11 standard introduced the possibility to create user-defined literals, that are basically built-in type literals (integer, float, char or string) followed by a used-defined suffix. User-defined literals enable the creation of new objects based on the built-in literal value and the applied user-defined suffix.

A bit of theory

A user-defined literal is treated as a call to a literal operator or a literal operator template. User-defined literals have two forms:

  • raw: a sequence of characters; the literal 0xBAD is in raw form is ‘0’, ‘x’, ‘B’, ‘A’, ‘D’
  • cooked: is the compiler interpreted type of the sequence of characters; the literal 0xBAD is the integer 2898 in cooked form.

User-defined literals:

  • support only the suffix form; defining prefixes is not possible;
  • begin with a underscore (‘_’); all suffixes that begin with any other character except underscore are reserved by the standard;
  • can be extended in both raw and cooked form; the exception is represented by strings that can only be extended in the cooked form

Cooked literals

The literal operator called for a cooked literal has following form:

Only several input types are allowed:

  • for integral literals (decimal, octal, hexadecimal or binary) the type is unsigned long long (the reason for unsigned is that the sign is not part of a numeric literal, but is in fact a unary operator applied to the numerical value).
  • for floating point types the type is long double:
  • for characters the type is char, wchar_t, char16_t or char32_t:
  • for strings the type is char const *, wchar_t const *, char16_t const * or char32_t const *:

Raw literals

Raw literals are supported only for integral and floating point types. The literal operator called for a cooked literal has following form (notice that the operator does not take a second parameter to indicate the size, the string is null-terminated):

Parsing this array of characters may involve loops, variable declaration, function calls, etc. As a result this form of the literal operator cannot be constexpr, which means it cannot be evaluated at compile time.

An alternative way of processing raw literals is with a literal operator variadic template. The purpose of a variadic template literal operator is to make the literal transformation at compile time. The form of the literal operator template is:

A bit of practice

Let’s take the following example where we declare a buffer of 4 KB.

This is identical to the following declaration (you’d usually expect)

It is made possible by the existence of a literal operator with the following form:

If the literal operator was not a constexpr then the compiler would trigger an error when declaring the buffer variable, because the size of the array must be known at compile time. You’d still be able to use the user-defined literal but in runtime contexts, such as sizing a vector.

In the next example we define a user-defined literal for expressing temperatures in Fahrenheit degrees. Supposing the Celsius degrees are the norm, we can write sometime like this:

and use it like in the following example:

The return type of the literal operator can be any type; it does not have to be a built-in type like in the previous examples. Given the following hierarchy of classes we can create user-defined literals that enable the creation of developer and quality assurer objects:

In the next example we want to express latitudes, such as 66°33’39”N (the Arctic Circle). (Notice that the following types and just some simple implementations for demo purposes only).

With this in place we can create objects like this:

Values like Latitude(66, 0, 0) are not very intuitive. Even though it’s more verbose it may be more desirable to be able to create objects like this:

That is possible if we define deg(), min() and sec() as following:

User-defined literals makes is more simple and more natural. By transforming the above functions into literal operators we can simplify the syntax.

As a result we can now create latitudes like this:

It should be very simple to develop this to support longitudes. You don’t have to add more literal operators, just the Longitude type and the appropriate overloaded operators for it.

Standard user-defined literals

C++14 defines several literal operators:

  • operator""if, operator""i and operator""il for creating a std::complex value

  • operator""h, operator""min, operator""s, operator""ms, operator""us, operator""ns for creating a std::chrono::duration value

    This is equivalent to the following (longer) form in C++11:

  • operator""s for converting a character array literal to a std::basic_string

Notice that all these literal operators are defined in separate namespaces that you have to use.

References

Compiler support

User defined literals are supported by major compilers starting with the following version:

See also:

Five new algorithms to C++11 that you should know about

C++11 added a bunch of new general purpose algorithms to the <algorithm> header. In this article we will look at five of them that C++ developers should know about.

all_of, any_of and none_of

These are actually three, not just a single algorithm, all_of, any_of, none_of, but they are very similar. They check if the supplied unary predicate return true for all, any or no element in a range.

Here are several examples:

is_sorted and is_sorted_until

The first algorithm, is_sorted, checks if the elements of the range are sorted ascending. There are two overloads of the function, the first uses operator< and the second takes a comparison function (that return true if the first element is less than the second) and uses that for comparing the elements in the range.

The second algorithm, is_sorted_until, is similar in that it checks that the elements of a range are sorted ascending. However, the function does not return a boolean value, but an iterator to the upper bound of the largest sorted sub-range (starting at the beginning of the examined range), i.e. the next beyond the last sorted element. There are two overloads, the first uses operator< and the second takes a comparison function, just like is_sorted does.

The output for this sample is:

is_partitioned

Algorithm is_partitioned checks whether a range is partitioned, i.e. sorted according to the supplied unary predicate so that all elements that satisfy the predicate come before all elements that do not satisfy the predicate. The function returns true if the range is empty.

is_permutation

Algorithm is_permutation determines whether a range is a permutation of another range. There are two overloads, the first uses operator== to compare the elements of the two ranges and the second takes a binary predicate (that returns true if two elements are equal).

minmax_element

The minmax_element algorithm finds both the minimum and the maximum element in a range and returns a pair of iterators to these elements. It is important to note that:

  • if the range is empty it returns std::make_pair(first, first)
  • if there is more than one element equal to the minimum value it returns an iterator to the first of these elements
  • if there is more than one element equal to the maximum value it returns an iterator to the last of these elements

There are two overloads, the first uses operator< to compare elements and the second uses a provided comparison function.

The output is:

C++ generic numeric algorithms in header <numeric>

The C++ Standard Library header <numeric> contains several generic numeric algorithms. In this post we take a look at how they can be used for solving real world examples.

Accumulating values

Problem: Given the monthly sales values compute the total sales during a year.

Solution: This is a simple sum that can be computed by iterating over the sales and summing them.

There is an algorithm for that called accumulate. It computes the sum in a given range and the provided initial value. So for our problem this can be put as:

Problem: Given the monthly inflation rates compute the total inflation during a year.

Solution: If the inflation was 10% in January and 20% in February, the inflation at the end of February is not 30% but 32%. The monthly inflation rates must be multiplied. An overloaded accumulate allows to specify a binary operation to be used for accumulating values, instead of operator+. So the solution to our problem could look like this:

Partial accumulations

Problem: Given the monthly sales values compute the accumulated total sales per whole year at the end of each month. In other words show the sales for January, January to February, January to March, … January to December.

Solution: This is again a simple summing operation where in each loop you have a partial sum. s[0] = v[0], s[1] = v[0] + v[1], s[2] = v[0] + v[1] + v[2], etc.

There is an algorithm called partial_sum that does exactly that: it computes the partial sums of the elements in the given range and writes them in a destination range. There are two overloads of it, one using operator+ and one that allows to specify a binary operation.

The content of acc_sales will be {1000, 2500, 4500, 6000, 8000, 9000, 12000, 13500, 14700, 16500, 18700, 20700}.

Sum of products

Problem: Given the values of daily sales in USD compute the total sales in EUR.

Solution: Computing the total sales in USD and then multiplying with the USD/EUR exchange rate is not a correct solution because the exchange rate varies every day. We must compute the daily sales in EUR and then sum those values. That means we need a sum of products.

Another algorithm in the <numeric> header called inner_product does exactly that. It takes two ranges and an initial value and uses operator* to compute the product and operator+ to sum the products.

Problem: Given the monthly budgets and the actual sales over an year count how many times the budget was met or exceeded.

Solution: To count how many times the sales where equal or greater than the budget we have to compare the values in each month and increment a value each time the condition was true.

Instead of coding this explicitly we could use an overload of the inner_product algorithm that takes two additional parameters, both binary operations, for the sum operation and the product operation. For the sum we can use std::plus() and for comparison std::greater_equal() (need to include header <functional>).

The result of the count for the input data is 6.

Adjacent differences

Problem: Given the monthly sales for an year compute the variations (in percentage) between the current and previous monthly sales. If sales in January were 1000 and in February were 1500, then the sales variation for February is 50%.

Solution: We have to iterate through the monthly value and compute (current - prev) / prev for each month. This is an operation applied to adjacent values.

An algorithm called adjacent_difference computes difference between adjacent values in a given ranges and writes them in a destination range. The first element of the input range is copied unmodified to the beginning of the destination range. An overload allows to specify a binary operation to be used instead of operator-.

To solve the proposed problem we call this algorithm on the sales and then remove the first element from the destination range (since it’s just a copy of the sales for the first month). We use a lambda for the binary operation and it simply returns (current - prev) / prev.

The result for the given range (shown with 4 decimals) is {0.5000, 0.3333, -0.2500, 0.3333, -0.5000, 2.0000, -0.5000, -0.2000, 0.5000, 0.2222, -0.0909}.

The standard way of converting between numbers and strings in C++11

In C++03 there was no standard way of converting numbers to strings. The best way to do that was using a std::stringstream:

One could put that into a more generic function that looks like this:

The opposite of converting a text to a number could look like this:

Of course, there was also the option of using C functions such as itoa, sprintf or atoi (or their Microsoft secure version _itoa_s, sprintf_s).

C++11 provides several standard functions for converting numbers to strings and strings to numbers, all of them available in the <string> header.

For converting numbers to strings there are two new overloaded functions: to_string() and to_wstring(). They take one argument of various numeric types (int, long, long long, double, long double, etc.) and return either a std::string or a std::wstring with the number converted to text.

These functions are actually just wrappers over sprintf and swprintf. According to the standard (section 21.5):

Each function returns a string object holding the character representation of the value of its argument that would be generated by calling sprintf(buf, fmt, val) with a format specifier of “%d”, “%u”, “%ld”, “%lu”, “%lld”, “%llu”, “%f”, “%f”, or “%Lf”, respectively, where buf designates an internal character buffer of sufficient size.

For the other way around of converting strings to numbers there are several overloaded methods (taking either a std::string or a std::wstring):

  • stoi: converts a string to a signed integer
  • stol: converts a string to a signed long
  • stoll: converts a string to a signed long long
  • stoul: converts a string to an unsigned long
  • stoull: converts a string to an unsigned long long
  • stof: converts a string to a float
  • stod: converts a string to a double
  • stold: converts a string to a long double

Functions stof, stod and stold are also just wrappers over strtod and strtold:

the first two functions call strtod(str.c_str(), ptr) and the third function calls strtold(str.c_str(), ptr). Each function returns the converted result, if any. The argument ptr designates a pointer to an object internal to the function that is used to determine what to store at *idx. If the function does not throw an exception and idx != 0, the function stores in *idx the index of the first unconverted element of str.

atoi() and atol() that convert a null-terminated byte-string (i.e. char*) to an integer or long were already available in header <cstdlib>. There is a new function available in this header called atoll() that converts a null-terminated byte string to a long long value.