Reputation: 31
I am trying to add a class object to a map, this is what I have:
#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()'
}
I don't understand why the constructor function is being called there, I thought newstud would already have been constructed from the previous line. Can anyone explain what is happening when I try to add newstud to the map?
Upvotes: 0
Views: 193
Reputation: 47784
std::map::operator[]
will insert new element into container if its not present, using default constructor, which in your case is not present and will probably doesn't make sense even if you provide one.
So use std::map::insert
for such scenario
Even if you successfully insert using studentList.insert(std::make_pair(name, newstud));
its not going to reflect changes in original map studentList
in main ( )
unless you use a reference type, in function definition & declaration of createStudent
So use
void createStudent(map<string, Student>& );
Upvotes: 2
Reputation: 116
In order to add entries using the function, you should make your parameter studentList
pass by reference.
And instead of
studentList[name] = newstud;
use:
studentList.insert(std::make_pair(name, newstud));
Just a suggestion, though.
Upvotes: 1