跟踪朋友和不说话的天数,动态记忆位置



我试图编写的程序是;编写一个程序,让用户跟踪他们最后一次与每个朋友交谈的时间。用户应该能够添加新朋友(想添加多少就添加多少!),并存储他们上次与每个朋友交谈的天数。让用户更新这个值(但不要让他们输入负值之类的假数字)。可以显示列表,该列表按的朋友的姓名排序,并按他们与每个朋友交谈后的最近时间排序。

以下是我迄今为止编写的代码。不太确定如何进步。

#include <iostream>
#include <string>
using namespace std;
struct User {
    string name;
    int noDays;
};
int *growArray (int * friends, int * size) {
    *size *= 2;
    int *new_friends = new int[*size];
    for (int i=0; i < *size; i++) {
        new_friends[i] = friends[i];
    }
    delete [] friends;
    return new_friends;
}
int main()
{
    User user;
    int control;
    int next_element = 0;
    int size = 10;
    int *friends = new int[size];
        if (size == next_element+1) {
            friends = growArray(friends, &size);
        }
        for (int i = 0; i < size; i++) {
        cout << "Please enter your friends name" << endl;
        cin >> user.name;
        cout << "Please enter no of days you last spoke to them" << endl;
        cin >> user.noDays;
        next_element++;
        }

    return 0;
}

我已经重写了上面的代码,您可以参考它(//表示已更改):

#include <iostream>
#include <string>
using namespace std;
struct User {
    string name;
    int noDays;
};
//Note: Return Types
User *growArray (User * friends, int * size) {
    //cout << "into growArray()n";
    User *new_friends = new User[*size * 2];
    for (int i=0; i < *size; i++) {
        new_friends[i].name = friends[i].name;
        new_friends[i].noDays = friends[i].noDays;
    }
    *size *= 2; //Place here
    delete [] friends;
    return new_friends;
}
int main()
{
    int size = 2;
    int next_element = 0;
    //struct array
    User *friends = new User[size]; 
    //use while instead of for
    while(1)
    {
        cout << "Please enter your friend's name (or q to exit):" << endl;
        cin >> friends[next_element].name;
        if (friends[next_element].name == "q")
        {
            break;
        }
        cout << "Please enter no of days you last spoke to them:" << endl;
        cin >> friends[next_element].noDays;
        if (size == ++next_element)
        {   
            //Return Types
            friends = growArray(friends, &size);
        }
    }
    //print result
    cout << "Do you want to print this list? (Y/N)";
    string choice;
    if (((cin >> choice) == "Y") || choice =="y")
    {
        cout << "List:n";
        for (int i = 0; i < next_element; i++)
        {
            cout << friends[i].name << 't' << friends[i].noDays << 'n';
        }   
    }
    //delete
    delete [] friends;
    return 0;   
}

最新更新