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 thestd::variant
template, which can store values of different types.std::variant<int, double, char> myVariantArray[5];
: Declares an array namedmyVariantArray
capable of holding 5 elements of different types:int
,double
, orchar
.myVariantArray[0] = 10;
,myVariantArray[1] = 3.14;
, ...: Assigns values to elements of themyVariantArray
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 anint
.std::cout << "Element is an integer: " << std::get<int>(element) << std::endl;
: Outputs the element if it is anint
.else if (std::holds_alternative<double>(element)) { ... }
: Checks if the current element in the array holds adouble
.std::cout << "Element is a double: " << std::get<double>(element) << std::endl;
: Outputs the element if it is adouble
.else if (std::holds_alternative<char>(element)) { ... }
: Checks if the current element in the array holds achar
.std::cout << "Element is a character: " << std::get<char>(element) << std::endl;
: Outputs the element if it is achar
.return 0;
: Indicates successful completion of themain()
function.