C++结构和动态分配的数组

C++ Structs and Dynamically Allocated Arrays

本文关键字:数组 动态分配 结构 C++      更新时间:2023-10-16

这就是我目前所拥有的。当我尝试将项目添加到数组时,程序崩溃。我正在寻找它来最终存储项目,以及获取当前时间,并将项目标记为未完成,直到用户输入"完成"。

无法使用 - 标准容器或智能指针

#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,您将很难进行排序。