gpt-3.5-turbo-0301· openai
Suzhen/CodeChat
编写一个模板类,能够存放大小为MAXSIZE的任意数据,类的功能包含:初始化、插入一个数据、读取一个数据,打印一个数据,对存放的数据排序等功能。思考:如果要能存放一个自定义类型的…
- User
编写一个模板类,能够存放大小为MAXSIZE的任意数据,类的功能包含:初始化、插入一个数据、读取一个数据,打印一个数据,对存放的数据排序等功能。思考:如果要能存放一个自定义类型的数据,对这个自定义类型有什么要求,可以自己尝试写写看哦~
- Assistant
以下是一个能存放最多10个数据的模板类,支持任意数据类型:
#include <iostream> #include <algorithm> using namespace std; template <typename T, int MAXSIZE> class Storage { private: T data[MAXSIZE]; int size; public: Storage() { size = 0; } void insert(T value) { if (size < MAXSIZE) { data[size++] = value; } } T read(int index) const { if (index >= 0 && index < size) { return data[index]; } return T(); } void print(int index) const { if (index >= 0 && index < size) { cout << data[index] << endl; } } void sort() { std::sort(data, data + size); } }; struct Person { string name; int age; bool operator < (const Person& other) const { return age < other.age; } }; int main() { Storage<int, 10> s1; s1.insert(3); s1.insert(1); s1.insert(4); s1.insert(2); s1.sort(); for (int i = 0; i < 4; i++) { s1.print(i); } Storage<Person, 10> s2; s2.insert({"Alice", 25}); s2.insert({"Bob", 35}); s2.insert({"Charlie", 30}); s2.sort(); for (int i = 0; i < 3; i++) { auto person = s2.read(i); cout << person.name << " " << person.age << 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.