Implement lại cho tôi một List trong C++
- User
Implement lại cho tôi một List trong C++
Assistant
cpp#include <iostream> #include <algorithm> template <typename T> class MyList { private: T* data; int size; int capacity; void resize(int newCapacity) { T* newData = new T[newCapacity]; std::copy(data, data + size, newData); delete[] data; data = newData; capacity = newCapacity; } public: // Constructor MyList() : data(nullptr), size(0), capacity(0) {} // Destructor ~MyList() { delete[] data; } // Add element to the end of the list void push_back(const T& element) { if (size == capacity) { resize(capacity == 0 ? 1 : capacity * 2); } data[size++] = element; } // Insert element at a specific index void insert(int index, const T& element) { if (index < 0 || index > size) { throw std::out_of_range("Index out of range"); } if (size == capacity) { resize(capacity == 0 ? 1 : capacity * 2); } std::copy_backward(data + index, data + size, data + size + 1); data[index] = element; size++; } // Remove element at a specific index void erase(int index) { if (index < 0 || index >= size) { throw std::out_of_range("Index out of range"); } std::copy(data + index + 1, data + size, data + index); size--; } // Access element at a specific index T& operator[](int index) { if (index < 0 || index >= size) { throw std::out_of_range("Index out of range"); } return data[index]; } // Get the size of the list int getSize() const { return size; } // Check if the list is empty bool isEmpty() const { return size == 0; } // Clear the list void clear() { delete[] data; data = nullptr; size = 0; capacity = 0; } }; int main() { MyList<int> myList; myList.push_back(10); myList.push_back(20); myList.push_back(30); std::cout << "Size: " << myList.getSize() << std::endl; for (int i = 0; i < myList.getSize(); i++) { std::cout << myList[i] << " "; } std::cout << std::endl; myList.insert(1, 15); std::cout << "Size after insert: " << myList.getSize() << std::endl; for (int i = 0; i < myList.getSize(); i++) { std::cout << myList[i] << " "; } std::cout << std::endl; myList.erase(2); std::cout << "Size after erase: " << myList.getSize() << std::endl; for (int i = 0; i < myList.getSize(); i++) { std::cout << myList[i] << " "; } std::cout << std::endl; return 0; }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.