C++结构和动态分配的数组
C++ Structs and Dynamically Allocated Arrays
这就是我目前所拥有的。当我尝试将项目添加到数组时,程序崩溃。我正在寻找它来最终存储项目,以及获取当前时间,并将项目标记为未完成,直到用户输入"完成"。
无法使用 - 标准容器或智能指针
#include <iostream>
#include <algorithm>
#include <string>
#include <iomanip>
#include <ctime>
using namespace std;
struct List{
string items;
char completed;
int time_t;
};
int main()
{
// Declare Variables
int userChoice = 0;
int numItems = 0;
int count = 0;
List* list = new List[];
// Get current time
time_t recordedTime = time(nullptr);
tm localTime = *localtime(&recordedTime);
// Give the user some options
cout << "1. Add Item" << endl;
cout << "2. Remove Item" << endl;
cout << "3. Sort Items" << endl;
cout << "4. Mark as Completed" << endl;
cout << "5. Exit" << endl;
cout << "Enter the number of the operation you wish to perform: ";
cin >> userChoice;
cout << endl;
// Perform the operation
switch(userChoice)
{
case 1:
{
cin.ignore(50, 'n');
cout << "Enter one item per line, or enter 'done' to finishn";
while(true)
{
do{
count++;
cout << "Item" << count << ": ";
getline(cin, list[count].items);
}
while(list[count].items !="done");
if(list[count].items == "done")
{
break;
}
}
}
break;
case 2:
{
}
break;
case 3:
{
}
break;
case 4:
{
cout << "Item #: ";
}
break;
case 5:
{
return 0;
}
}
// Output the list
cout << "-------Items-------" << endl;
cout << "Enter the number of the operation you wish to perform: ";
cin >> userChoice;
return 0;
}
我的建议是你应该使用vector
来包含你的所有项目。 但这会大大改变你的代码。
更简单的方法是将列表定义更改为 List* list = new List[1000];
这将分配一个大小为 1000 的数组,您之前的定义只分配一个List
,并使用指针list
指向它。
编辑
如果您不知道大小,则应使用 vector
将列表定义为 vector<List> list
,并使用 push_back
将项目追加到容器。
喜欢
{
cout << "Item" << count << ": ";
string str;
getline(cin, str);
List item {str, 'N', localtime};
list.push_back(move(item));
}
编辑
不能使用 stl,而且只有内存限制,我认为您必须将List
定义更改为LinkedList
,例如
struct List{
string items;
char completed;
int time_t;
List* next;
};
并且每次输入时分配内存,您必须有另一个指针来记住您输入的最后一项。如果您不使用 STL,您将很难进行排序。
相关文章:
- 字符指针数组内存分配
- 当按下 SFML C++时,如何在数组中分配值
- C++编译时使用 constexpr 字符数组指针分配静态数组?
- 将数组动态分配到具有指针参数的函数中
- C++ 无法将字符数组变量分配给字符串变量
- 使用 new: "potentially uninitialized pointer"将对象数组动态分配给指针
- 为什么C 没有方便的方式来为多维数组动态分配内存
- 动态数组仅分配一个元素
- c++中的数组动态内存分配
- 多维数组动态分配的内存图
- 如何在 c++ 中使用 2-D 固定数组为 4-D 数组动态分配内存
- 动态数组内存分配如何工作
- C++中高维数组动态内存分配的正确方法.
- 从 C++ 结构中包含的指针数组动态分配和访问内存
- 对象数组动态内存分配
- 为二维数组动态分配内存时出错
- 如何将2d数组动态分配给结构
- 为结构数组c++动态分配内存
- 简单的数组内存分配与大小动态分配和预定的大小
- 分配对象数组动态冻结