ESP32 cpplinq: The take operator

In this esp32 tutorial we will learn how to use the cpplinq take operator. The tests shown on this tutorial were performed using an ESP32 board from DFRobot, running the Arduino core.

Introduction

In this tutorial we will learn how to use the cpplinq take operator. This operator allows to create a new sequence from an original one by taking a given number of elements and skipping the remaining.

In a concrete use case, if we have for example an array of 10 elements and we pass the value 4 to the take operator, the final array will only have the first 4 elements.

The tests shown on this tutorial were performed using an ESP32 board from DFRobot, running the Arduino core.

The code

As usual, we start by including the cpplinq library, followed by the declaration of the use of the cpplinq namespace.

#include "cpplinq.hpp"
using namespace cpplinq;

Moving on to the Arduino setup function, where we will write the rest of our code, we start by opening a serial connection, to be able to output the result of our program.

After this we will declare an array with 9 elements, over which we will later apply the take operator.

Serial.begin(115200);
int ints[] = {1,2,3,4,5,6,7,8,9};

Then we will proceed to convert the array into a range object, so we can apply the cpplinq operators.

from_array(ints)

Then we will apply the take operator. As already hinted in the introductory section, this operator receives as argument an integer value, specifying how many elements we should take from the original range. The resulting range will contain the elements that we have specified.

For this tutorial we will pass the value 4. This means the 4 first elements of the original range should be taken. These should be the values 1, 2, 3 and 4.

take(4)

After this we just need to convert our range to a C++ vector, allowing us to iterate over it and print all the elements.

The full chain of operator invocations can be seen below and already contains the call to the to_vector operator, which performs the mentioned conversion to a vector.

auto result = from_array(ints)
>> take(4)
>> to_vector();

To finish our code, we will iterate over all elements of the vector and print them to the serial port.