Jason Pan
Jason Pan

Reputation: 792

Can I pass a nested initializer_lists with different nested level in C++?

I am constructing a NestedInteger class to store mixed type of int, or vector of int, or vector of vector of int. For example: {1, {2, {3, 4}}, 5}. It seems that the element types in the list should be the same, because I declare the constructor as this:

template <typename T>
NestedInteger(const std::initializer_list<T> l);

The elements should have same type T.

Is there a method to pass a list like this {1, {2, 3}, 4}?

Upvotes: 0

Views: 67

Answers (1)

molbdnilo
molbdnilo

Reputation: 66459

Use std::initializer_list<NestedInteger> for the parameter, and provide a constructor for single integers.

Example:

struct NestedInteger
{
    NestedInteger(int x): stuff(x) {}
    NestedInteger(std::initializer_list<NestedInteger> xs): stuff(xs) {}
    
    std::variant<int, std::vector<NestedInteger>> stuff;
};

Test code:

std::ostream& operator<<(std::ostream& os, const NestedInteger& is)
{
    if (std::holds_alternative<int>(is.stuff))
    {
        os << std::get<int>(is.stuff);
    }
    else
    {
        os << "{ ";
        for (const auto& it: std::get<std::vector<NestedInteger>>(is.stuff))
        {
            os << it << ' ';
        }
        os << '}';
    }
    return os;
}


int main()
{
    NestedInteger nest = {1,2,{3,4},{5,{6,{7,8}}},9};
    std::cout << nest << endl;
}

Output:

{ 1 2 { 3 4 } { 5 { 6 { 7 8 } } } 9 }

Upvotes: 1

Related Questions