In this tutorial we will learn how to create and use a C++ pair. The code we will cover below works both on the ESP32 and on the ESP8266. The tests on the ESP32 were performed using a DFRobot’s ESP-WROOM-32 device integrated in a ESP32 FireBeetle board. The tests on the ESP8266 were performed on a DFRobot’s ESP8266 FireBeetle board.
In this tutorial we will learn how to create and use a C++ pair. The code we will cover below works both on the ESP32 and on the ESP8266. We will be using the Arduino core to do our tests.
A pair is a class that allows to group together two elements that might be of different types . Nonetheless, we can also use a pair to group elements of the same type.
Each value of the pair can then be accessed by its public members: first and second . We can also assign new values to each member.
Note that the pair belongs to the std namespace, which means that, when accessing this data type, we need to either declare the using of the std namespace or use the scope resolution operator:
For this tutorial we don’t need to import any libraries. So we will move on to the Arduino setup function, where we will start by opening a serial connection.
After that we are going to define our pair. Since the pair class belongs to the std namespace, we need to use this prefix followed by the scope resolution operator ::, followed by our data type, like already mentioned in the introductory section:
The pair class has two template parameters that we need to specify . The first template parameter corresponds to the type of the first element of the pair, and the second template parameter corresponds to the type of the second element of the pair.
In our case, for this introductory tutorial, we will assume that we will have an integer as first element and a string as second.
std::pair <int, char *>
As first input of the constructor we will pass an integer (the data type of the first element) and as second input we will pass a string (the data type of the second element).
Note however that this class has other constructor signatures, as can be seen here. We are not going to use them in this tutorial, but it is important to understand the different alternatives we have.
To test the code, simply compile it and upload it to your device using the Arduino IDE. When the procedure finishes, open the IDE serial monitor.
You should get an output similar to figure 1. As can be seen, in the first lines, we got the content that we have used to initialize our pair. After that, we have updated the content of both of its elements, and in the next lines printed we obtained those values, as expected.
Figure 1 – Output of the program, showing the original content and the updated content of the pair. Taken from the tests on the ESP32.