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.
12 messages · Page 1 of 1 (latest)
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.
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
What is your question?
That is not a questiob
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 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.
!solved