我正在尝试使用map
为每个学生安排我的输出,这是根据姓名和ic号码生成的密码。我希望输出以编号列表的形式排列。在我在线搜索之后,我发现可以使用index或int来完成。我正在上的这门课是关于数据结构的,它很大程度上倾向于程序的效率。我已经设法得到了我想要的输出,但我想问一下,哪种方法更有效或更好。如果你不明白我在说什么,很抱歉,我的解释技巧非常糟糕。如果有任何可以改进的地方,请让我知道。TQVM。
通过int:
void displayStudent(map<string, string>& studentMap) {
map<string, string>::iterator displayStudentAndPassword = studentMap.begin();
int i = 1;
for (displayStudentAndPassword = studentMap.begin(); displayStudentAndPassword != studentMap.end(); displayStudentAndPassword++) {
cout << i << ". " << displayStudentAndPassword->first << ":- " << displayStudentAndPassword->second << endl;
cout << endl;
i++;
}
}
按索引:
void displayStudent(map<string, string>& studentMap) {
map<string, string>::iterator displayStudentAndPassword = studentMap.begin();
int index = 1;
for (displayStudentAndPassword = studentMap.begin(); displayStudentAndPassword != studentMap.end(); displayStudentAndPassword++) {
cout << index << ". " << displayStudentAndPassword->first << ":- " << displayStudentAndPassword->second << endl;
cout << endl;
index++;
}
}
输出图像
发布于 2020-12-11 03:25:00
据我所知,这两个解决方案是相同的。唯一的区别是您为跟踪索引号而对变量进行了不同的命名。您在一个"index“中将其命名为"i”,而在另一个“index”中将其命名为“i”。在这种情况下,您没有将其用作索引。您只是在对输出进行编号。通过使用地图,没有索引号。相反,您有一个键,它是std::map。
贴图非常适合于从一个对象快速映射到另一个对象。在这种情况下,从一个字符串到另一个字符串。大概这样你就可以从一个学生的名字映射到他们存储的密码。但是,如果您在其他地方的代码不需要这个,那么我建议使用矢量而不是映射。因为它基本上是由索引引用的对象数组。当然,包含在向量中的对象必须是一个类或结构,以保存名称和密码这两个值。
https://stackoverflow.com/questions/65245192
复制