向映射添加类

Adding a class to a map

本文关键字:添加 映射      更新时间:2023-10-16

我想添加一个类对象到一个地图,这是我有:

#include<vector>
#include<map>
#include<stdio.h>
#include<string>
#include<iostream>
using namespace std;
class Student{
    int PID;
    string name;
    int academicYear;
public:
    Student(int, string, int);
};
Student::Student (int P, string n, int a) {
    PID = P;
    name = n;
    academicYear = a;
}
void createStudent(map<string, Student>);
int main(int argc, char** argv){
    map <string, Student> studentList;
    createStudent(studentList);
}

void createStudent(map<string, Student> studentList){
    int PID;
    string name;
    int academicYear;
    cout << "Add new student-nName: ";
    getline(cin, name);
    cout << "PID: ";
    cin >> PID;
    cout << "Academic year: ";
    cin >> academicYear;
    Student newstud (PID, name, academicYear);
    studentList[name] = newstud;  //this line causes the error: 
                                  //no matching function for call to 
                                  //'Student::Student()'
}

我不明白为什么构造函数在那里被调用,我以为newstud已经从上一行构造了。有人能解释一下,当我试图在地图上添加newstud时发生了什么吗?

    <
  • 问题1日/gh>

std::map::operator[] 将使用默认构造函数将新元素插入到容器中,如果它不存在,在您的情况下,它不存在,即使您提供了一个也可能没有意义。

所以使用 std::map::insert 对于这种情况

  • 问题2

即使你成功地使用studentList.insert(std::make_pair(name, newstud));插入,它也不会在main ( )中反映原始映射studentList的变化,除非你在函数定义中使用引用类型&createStudent的声明

所以使用

void createStudent(map<string, Student>& );

为了使用函数添加条目,您应该使参数studentList通过引用传递。

而不是

studentList[name] = newstud; 

使用:

studentList.insert(std::make_pair(name, newstud));

只是个建议。