an array that take different data type c++

#include <iostream>
#include <variant>

int main() {
    std::variant<int, double, char> myVariantArray[5];

    myVariantArray[0] = 10;
    myVariantArray[1] = 3.14;
    myVariantArray[2] = 'a';
    myVariantArray[3] = 20;
    myVariantArray[4] = 4.2;

    for (const auto &element : myVariantArray) {
        if (std::holds_alternative<int>(element)) {
            std::cout << "Element is an integer: " << std::get<int>(element) << std::endl;
        } else if (std::holds_alternative<double>(element)) {
            std::cout << "Element is a double: " << std::get<double>(element) << std::endl;
        } else if (std::holds_alternative<char>(element)) {
            std::cout << "Element is a character: " << std::get<char>(element) << std::endl;
        }
    }

    return 0;
}

Explanation:

  • #include <iostream>: Includes the input-output stream header file for handling input and output operations.
  • #include <variant>: Includes the header file for using the std::variant template, which can store values of different types.
  • std::variant<int, double, char> myVariantArray[5];: Declares an array named myVariantArray capable of holding 5 elements of different types: int, double, or char.
  • myVariantArray[0] = 10;, myVariantArray[1] = 3.14;, ...: Assigns values to elements of the myVariantArray array using different data types (int, double, char).
  • for (const auto &element : myVariantArray) { ... }: Iterates through each element of the array using a range-based for loop.
  • if (std::holds_alternative<int>(element)) { ... }: Checks if the current element in the array holds an int.
  • std::cout << "Element is an integer: " << std::get<int>(element) << std::endl;: Outputs the element if it is an int.
  • else if (std::holds_alternative<double>(element)) { ... }: Checks if the current element in the array holds a double.
  • std::cout << "Element is a double: " << std::get<double>(element) << std::endl;: Outputs the element if it is a double.
  • else if (std::holds_alternative<char>(element)) { ... }: Checks if the current element in the array holds a char.
  • std::cout << "Element is a character: " << std::get<char>(element) << std::endl;: Outputs the element if it is a char.
  • return 0;: Indicates successful completion of the main() function.