向映射添加类
Adding a class to a map
我想添加一个类对象到一个地图,这是我有:
#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));
只是个建议。
相关文章:
- QT通过C++添加映射QML项目
- 添加静态constexpr成员是否会更改结构/类的内存映射
- 无法添加多个键以映射将结构作为键
- 添加要映射的对象的唯一指针
- 将相同的键添加到低序映射
- 在具有 std::p air 键和值的映射中添加 b2vec2
- 添加字符串向量和不同数据类型向量的映射
- 无法将元素添加到 STL 映射
- 将数据添加到现有类,而无需继承、映射或修改类
- C++静态初始化顺序:添加到映射中
- C++构造函数期间向映射添加"self"
- 如何在类中添加结构,结构的向量以映射
- 在向量上迭代,并添加迭代器实际指向的对象作为映射中的键
- 相同的密钥(使用malloc创建)添加了两次映射
- 添加多个元素以映射<pair> c++
- 如何自动将处理程序添加到全局映射
- C++ - 使用 lambda 将映射添加到映射
- C 将条目添加到具有字符串和类实例的STL映射中,作为指针
- 从 LLVM 添加映射到C++ lambda
- 在(c++) cocos2dx中添加映射对象到Vector