Как сделать так, чтобы содержимое списка попадало в неупорядоченную карту, используя функцию в качестве аргумента? - PullRequest
0 голосов
/ 20 ноября 2018

Я ищу в основном то, что заголовок;контекст, необходимый для кода, показан ниже.После этого я также хочу отобразить карту на экране, а затем удалить все содержимое списка и карту перед их очисткой.Вот мой код:

int main()
{
    list<Student *> tAllStudents;
    unordered_map<int, Student*> tSuperMap;
    while (true)
    {
        int a;
        string b;
        double c;
        cout << "What is the ID of the student? Enter -1 to cancel.";
        cin >> a;
        if (a == -1) { break; }
        else
        {
            cout << "What is the last name of the student?";
            cin >> b;
            cout << "What is the student's GPA?";
            cin >> c;

            Student* newS = new Student(a, b, c);
            tAllStudents.push_back(newS);
        }
    }
    for (auto iter = tAllStudents.begin(); iter != tAllStudents.end(); iter++)
    {
        /*here should be where it's done, where the ID (an internal variable in student) is the key, and the value is the Student object itself, which when the list prints will display its 'LastName' and 'GPA' as well*/
    }
}

Любая другая помощь также приветствуется!

1 Ответ

0 голосов
/ 20 ноября 2018
   #include<list>
   #include<map>
   #include<unordered_map>
   #include<memory>
   #include<string>
   #include<iostream>

   using namespace std;

   struct Student{
    Student(int a, string b, double c) : ID(a) ,
    Name(b),
    Gpa(c){}
    int ID;
    string Name;
    double Gpa;
   };

   int main()
   {
    list<std::unique_ptr<Student>> tAllStudents;
    std::unordered_map<int, unique_ptr<Student>> tSuperMap;
    while (true)
    {
        int a;
        string b;
        double c;
        cout << "What is the ID of the student? Enter -1 to cancel.";
        cin >> a;
        if (a == -1) { break; }
        else
        {
            cout << "What is the last name of the student?";
            cin >> b;
            cout << "What is the student's GPA?";
            cin >> c;

            //Student* newS = new Student(a, b, c);
            tAllStudents.push_back(make_unique<Student>(a,b,c));
        }
    }
    for (auto iter = tAllStudents.begin(); iter != tAllStudents.end(); iter++)
    {
        /*here should be where it's done, where the ID (an internal variable in student) is the key, and the value is the Student object itself, which when the list prints will display its 'LastName' and 'GPA' as well*/
        tSuperMap[(*iter)->ID] = std::move(*iter);    

    }
    return 0;
}

Если вы должны хранить указатель в контейнере, используйте unique_ptr или shared_ptr.Вставка карты происходит, когда вы даете ей новый ключ.unordered_map ничем не отличается, поскольку это хеш-контейнер.У вас уже есть итерация контейнера.Я уверен, что вы можете выяснить, как напечатать объект вашей карты.

...