#bad_variant_access... Help

12 messages · Page 1 of 1 (latest)

teal martenBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

pseudo zinc
#

help

#include <iostream>
#include <variant>

template <typename... Types> class DynamicArray {
public:
    DynamicArray(std::size_t initial_capacity) : capacity(initial_capacity), length(0) {
        data = new std::variant<Types...>[initial_capacity];
    }

    ~DynamicArray() {
        delete[] data;
    }

    template <typename T> void append(const T& value) {
        if (length == capacity) {
            capacity *= 2;
            std::variant<Types...>* new_data = new std::variant<Types...>[capacity];

            for (std::size_t i = 0; i < length; ++i) {
                new_data[i] = data[i];
            }

            delete[] data;
            data = new_data;
        }

        data[length++] = value;
    }

    template <typename T> T& get(std::size_t index) {
        return std::get<T>(data[index]);
    }

    std::size_t size() const {
        return length;
    }

private:
    std::variant<Types...>* data;
    std::size_t capacity;
    std::size_t length;
};

int main() {
    DynamicArray<int, double, char> myArray(5);

    myArray.append(42);
    myArray.append(3.14);
    myArray.append('A');

    for (std::size_t i = 0; i < myArray.size(); ++i) {
        std::cout << "Element " << i << ": " << myArray.get<int>(i) << std::endl;
    }

    return 0;
}
#

bad variant access error

sinful thunder
#

What is your question?

pseudo zinc
#

i need help with this code

#

bad_variant

sinful thunder
#

That is not a questiob

pseudo zinc
#

bad_variant... Help

#

bad_variant_access... Help

teal martenBOT
#

Thank you and let us know if you have any more questions!

This thread is now set to auto-hide after an hour of inactivity

#

@pseudo zinc

Please Do Not Delete Posts!

Please don't delete forum posts. They can be helpful to refer to later and other members can learn from them. In the future you can use !solved to close a post and mark a post as solved.

pseudo zinc
#

!solved