Using C++ STL functions instead of loops – EasyHack

C++ Standard library, which resides in std:: namespace provides common classes and functions which can be used by developers. Among them, Standard Template Library (STL) provides classes and functions to better manage data through data structures named containers. Here I discuss how to use STL functions for better processing of data, and avoid loops.

Checking Conditions

To iterate over a container to see if some specific condition is valid for all, any, or none of the elements in that container, C/C++ developers traditionally used loops.

On the other hand, since C++11, there are functions that can handle such cases: all_of, any_of and none_of. These functions process STL containers, and can replace loops. If you want to know if a function returns true for all, any, or none of the items of the container, then you can simply use these functions. This is the EasyHack dedicated to such a change:

Here is an example patch which uses any_of instead of a loop:

-    bool bFound = false;
     // convert ASCII apostrophe to the typographic one
     const OUString aText( rOrig.indexOf( '\'' ) > -1 ? rOrig.replace('\'', u'’') : rOrig );
-    size_t nCnt = aVec.size();
-    for (size_t i = 0;  !bFound && i < nCnt;  ++i)
-    {
-        if (aVec[i] == aText)
-            bFound = true;
-    }
+    const bool bFound = std::any_of(aVec.begin(), aVec.end(),
+        [&aText](const OUString& n){ return n == aText; });

As you can see, the new code is more concise, and avoids using loops.

Conditional Copying, Removing and Finding

If you want to copy, remove or simply find a value in a container which conforms to a specific functions, you may use copy_if, remove_if or find_if.

Again, this is an example patch:

-  for ( size_t i = 0; i < SAL_N_ELEMENTS( arrOEMCP ); ++i )
-        if ( arrOEMCP[i] == codepage )
-            return true;
-
-    return false;
+    return std::find(std::begin(arrOEMCP), std::end(arrOEMCP), codepage) != std::end(arrOEMCP);

Final Words

Refactoring code is a good way to improve knowledge on LibreOffice development. The above EasyHacks are among EasyHacks that everyone can try.

More information about EasyHacks, and how to start working on them can be found on TDF Wiki:

Leave a Reply

Your email address will not be published. Required fields are marked *

I accept the Privacy Policy