Reputation: 1
I am trying to create an array of integers but I do not want all values of that array to be of type integer. I want to store null
in some places and integers in other places. eg.
arr[] = {50, 20, null, 30, null, null, 60}
In java, I am aware that you can declare the array is Integer and store null
(Integer[] arr
). Is there any way I can do the same for C++?
Upvotes: 0
Views: 1517
Reputation: 6326
You can't store values types with different types in the array(Actually there is no java's null in C++ ). But you can store pointers, and leave the null value with nullptr pointer. Or store std::any/std::optional into array with c++17.
#include <any>
#include <array>
#include <memory>
#include <vector>
#include <optional>
int main(int argc, char* argv[]) {
std::array<std::unique_ptr<int>, 7> ar1 = {std::make_unique<int>(50),
std::make_unique<int>(20),
nullptr,
std::make_unique<int>(30),
{},
{},
std::make_unique<int>(60)};
std::array<std::any, 7> ar2 = {50, 20, {}, 30, {}, {}, 60};
std::array<std::optional<int>, 7> ar3 = {50, 20, {}, 30, {}, {}, 60};
return 0;
}
Upvotes: 2