BogoToBogo
  • Home
  • About
  • Big Data
  • Machine Learning
  • AngularJS
  • Python
  • C++
  • go
  • DevOps
  • Kubernetes
  • Algorithms
  • More...
    • Qt 5
    • Linux
    • FFmpeg
    • Matlab
    • Django 1.8
    • Ruby On Rails
    • HTML5 & CSS

C++ Tutorial - Functors(Function Objects) II - 2020

cplusplus_icon.png




Bookmark and Share





bogotobogo.com site search:




Converting functions to functors

We can convert a function to a functor.

#include <iostream>
#include <vector>
#include <set>
#include <algorithm>
#include <functional>  // std:: bind
#include <cmath>
#include <iterator>    // back_inserter

double power(double a, double b)
{
	return pow(a,b);
}

int main()
{
    std::set<int> s = { 1, 2, 3, 4, 5 };
    std::vector<int> v;
    auto fnc = std::function <double (double,double)>(power); // C++11
    std::transform(s.begin(), s.end(), 	
             std::back_inserter(v), 
             std::bind(fnc, std::placeholders::_1, 3));  // C++11
	         // {1, 8, 27, 64, 125}
}

The transform() takes set elements, raise each of them to the power of 3, and put it into a vector container using back_inserter(). The function template class converts our power function int fnc. This is only available in C++11. In C++03, we should use ptr_fun.


Alternatives to functors

Sometimes, programming logic written using functor is not easily readable. In that case, we need to seek other options. For example:

#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>  // std:: bind
#include <cmath>
#include <iterator>    // back_inserter

int main()
{
    std::vector<int> v1 = { 101, 2, 38, 64, 55 };
    std::vector<int> v2;

    std::transform(v1.begin(), v1.end(),   // source
             std::back_inserter(v2),       // destination
             std::bind(std::logical_or<bool>(),
                       std::bind(std::greater<int>(), std::placeholders::_1, 100),
                       std::bind(std::less<int>(), std::placeholders::_1, 10))
	          );  // C++11 (bind)
	          // element > 100 or element < 10
}

It checks if(i > 100 || i < 10) where i is an element from v1. Then, it puts either 1 or 0 into v2 depending on the result of the check. In this case, it looks like this:

v2 = {1, 1, 0, 0, 0}

If we want to see the output, we can replae the back_inserter() line with this:

std::ostream_iterator<int>(std::cout, " "),   // destination

Anyway, the code is a little bit verbose and not easily read. So, we can modify it like this:

bool isTrue(int i)
{
    return (i > 100 || i < 10);
}

int main()
{
    std::vector<int> v1 = { 101, 2, 38, 64, 55 };
    std::vector<int> v2;

    std::transform(v1.begin(), v1.end(),    // source
             std::back_inserter(v2),        // destination
	     isTrue
	);   
	// element > 100 or element < 10
}

Or we can use C++11's lambda function:

    std::transform(v1.begin(), v1.end(),    // source
             std::back_inserter(v2),        // destination
	     [](int e){return ( e > 100 || e < 10); }
	);   

Note that with the lambda function, we do not have to define a separate function and just use anonymous function which makes code more compace, at least in this case.

  1. Functors (Function Objects) I - Introduction
  2. Functors (Function Objects) II - Converting function to functor
  3. Functors (Function Objects) - General




Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization

YouTubeMy YouTube channel

Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong






Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong






C++ Tutorials

C++ Home

Algorithms & Data Structures in C++ ...

Application (UI) - using Windows Forms (Visual Studio 2013/2012)

auto_ptr

Binary Tree Example Code

Blackjack with Qt

Boost - shared_ptr, weak_ptr, mpl, lambda, etc.

Boost.Asio (Socket Programming - Asynchronous TCP/IP)...

Classes and Structs

Constructor

C++11(C++0x): rvalue references, move constructor, and lambda, etc.

C++ API Testing

C++ Keywords - const, volatile, etc.

Debugging Crash & Memory Leak

Design Patterns in C++ ...

Dynamic Cast Operator

Eclipse CDT / JNI (Java Native Interface) / MinGW

Embedded Systems Programming I - Introduction

Embedded Systems Programming II - gcc ARM Toolchain and Simple Code on Ubuntu and Fedora

Embedded Systems Programming III - Eclipse CDT Plugin for gcc ARM Toolchain

Exceptions

Friend Functions and Friend Classes

fstream: input & output

Function Overloading

Functors (Function Objects) I - Introduction

Functors (Function Objects) II - Converting function to functor

Functors (Function Objects) - General



Git and GitHub Express...

GTest (Google Unit Test) with Visual Studio 2012

Inheritance & Virtual Inheritance (multiple inheritance)

Libraries - Static, Shared (Dynamic)

Linked List Basics

Linked List Examples

make & CMake

make (gnu)

Memory Allocation

Multi-Threaded Programming - Terminology - Semaphore, Mutex, Priority Inversion etc.

Multi-Threaded Programming II - Native Thread for Win32 (A)

Multi-Threaded Programming II - Native Thread for Win32 (B)

Multi-Threaded Programming II - Native Thread for Win32 (C)

Multi-Threaded Programming II - C++ Thread for Win32

Multi-Threaded Programming III - C/C++ Class Thread for Pthreads

MultiThreading/Parallel Programming - IPC

Multi-Threaded Programming with C++11 Part A (start, join(), detach(), and ownership)

Multi-Threaded Programming with C++11 Part B (Sharing Data - mutex, and race conditions, and deadlock)

Multithread Debugging

Object Returning

Object Slicing and Virtual Table

OpenCV with C++

Operator Overloading I

Operator Overloading II - self assignment

Pass by Value vs. Pass by Reference

Pointers

Pointers II - void pointers & arrays

Pointers III - pointer to function & multi-dimensional arrays

Preprocessor - Macro

Private Inheritance

Python & C++ with SIP

(Pseudo)-random numbers in C++

References for Built-in Types

Socket - Server & Client

Socket - Server & Client 2

Socket - Server & Client 3

Socket - Server & Client with Qt (Asynchronous / Multithreading / ThreadPool etc.)

Stack Unwinding

Standard Template Library (STL) I - Vector & List

Standard Template Library (STL) II - Maps

Standard Template Library (STL) II - unordered_map

Standard Template Library (STL) II - Sets

Standard Template Library (STL) III - Iterators

Standard Template Library (STL) IV - Algorithms

Standard Template Library (STL) V - Function Objects

Static Variables and Static Class Members

String

String II - sstream etc.

Taste of Assembly

Templates

Template Specialization

Template Specialization - Traits

Template Implementation & Compiler (.h or .cpp?)

The this Pointer

Type Cast Operators

Upcasting and Downcasting

Virtual Destructor & boost::shared_ptr

Virtual Functions



Programming Questions and Solutions ↓

Strings and Arrays

Linked List

Recursion

Bit Manipulation

Small Programs (string, memory functions etc.)

Math & Probability

Multithreading

140 Questions by Google



Qt 5 EXPRESS...

Win32 DLL ...

Articles On C++

What's new in C++11...

C++11 Threads EXPRESS...

Go Tutorial

OpenCV...








Contact

BogoToBogo
contactus@bogotobogo.com

Follow Bogotobogo

About Us

contactus@bogotobogo.com

YouTubeMy YouTube channel
Pacific Ave, San Francisco, CA 94115

Pacific Ave, San Francisco, CA 94115

Copyright © 2024, bogotobogo
Design: Web Master