用动态内存管理创建类列表数组
Creating List Like Array with Dynamic Memory Management
有讲座班和学生班。我们正在尝试用数组保存课堂上的学生信息。
例如:Student * studentList = new Student[numberOfStudent];
studentAdd("Mary");
studentDelete("Mary");
问题:用户没有给出学生人数,当用户添加一个新的学生时,学生人数正在增加。所以我认为我需要一个像结构器一样的列表来保存它们,但这是禁止的。你有什么比我的临时解决办法更有效的办法吗?
我的临时解决方案:保存学生人数和数组大小,当学生人数大于数组大小时,将数组复制到一个比旧数组大的新数组。
这个问题与我的作业有关,我们通过
*使用指针动态分配内存
*不使用任何固定大小的静态数组或其他数据结构,如来自标准库的向量
如果不想使用对象,可以直接使用函数。注意,我没有编译这段代码。
#include <iostream>
#include <sstream>
#include <string>
#include "Student.h"
void add(Student **list, Student *rhs);
void destroy(Student **list,int const &idx);
void destroy(Student **list,const char* student_name); //find the student name and delete
void resize(Student **list,int const &idx);
Student** begin(Student **list,); //get the first Student
Student** end(Student **list,); //the end of the array
void clear(Student **list,); //drop all Students
int main(int argc, char **argv)
{
if(argc < 2)
{
stc::cerr << "not enough parameters" << std::endl;
}
istringstream buffer(argv[1]);
int value;
buffer >> value;
Student ** studentList = new *Student[value];
int s
add(studentList, "Mary");
destroy(studentList, "Mary");
return(0);
}
void add(Student **list, Student *rhs) { /*definition*/ }
void destroy(Student **list, int const &idx) { /*definition*/ }
void destroy(Student **list, const char* student_name) { /*definition*/ }
void resize(Student **list, int const &idx) { /*definition*/ }
Student** begin(Student **list) { /*definition*/ }
Student** end(Student **list) { /*definition*/ }
void clear(Student **list) { /*definition*/ }
现在把这些都定义好,就完成了
我不推荐这种方法
我将使用对象…并考虑到PaulMcKenzie所说的容量
class StudentList
{
private:
Student **list;
std::size_t size;
std::size_t capacity;
public:
StudentList(){}
~StudentList(){ this->clear(); }
inline void add(Student *rhs) { //definition }
inline void destroy(int const &idx) { //definition }
inline void destroy(const char* student_name) { //definition }
inline void resize(int const &idx) { //definition }
inline Student** begin() { //definition }
inline Student** end() { //definition }
inline void clear() { //definition }
};
如果可能的话
迭代器
在vector下面你会发现一个类似的实现,它使用Iterators来封装Student**
。
相关文章:
- C++如何生成std::数组列表
- 在数组中输入 n 个整数的列表,并以类似于钟摆来回移动的方式排列它们. 输入-1 3 2 5 4,输出5 3 1 2 4
- C++未知长度字符串的数组,其行为类似于 Python 字符串列表
- GTEST : 如何将数组列表作为参数传递到 ValuesIn of INSTANTIATE_TEST_CASE_P?
- 基于数组的列表 - 动态数组创建时出错
- 如何使用列表/数组在C++中实现 Python "... not in ..."?
- 从非托管 C# DLL 返回列表/数组
- C++对象列表数组
- 如何在C++中创建配对列表数组
- 链接列表数组
- 获取列表数组中的所有列表项
- 如何创建和扫描列表/数组..在嵌入式剪辑中
- 列表数组<string>,插入字符串行为奇怪
- 对 STL 列表数组使用迭代器的语法
- 在类|C++中创建分数列表数组
- C++是否有一些类似C#类型的东西来存储列表/数组中的类类型
- 列表数组-构造函数和main()中的地址不匹配
- c++中的列表数组.指针;/
- STL 列表数组无法访问列表函数
- 用动态内存管理创建类列表数组