【发布时间】:2019-05-10 06:32:39
【问题描述】:
此代码提示用户询问他们的姓名和他们就读的学校。将两者都存储到地图中(将名称存储到向量中)。然后我想以这种格式打印出学校和每个就读该学校的人的姓名。
学校:名字,名字,名字。 /new line School : name, name , name etc. . . .
我第一次在 java 中做,并试图转换为 c++,不确定我是否正确执行此操作,也不确定如何将底部的 for 循环转换为 c++(是否有类似于 java 中的 map.keySet() 的东西在 c++ 中?)
我不断收到 emplace() 错误,我做错了什么或需要#include 吗?
int main() {
//Program that takes in users school that they attend and prints out the people that go there
string name;
string school;
//create the map
map<string, vector<string> > sAtt;
do {
cout << "PLEASE ENTER YOUR NAME: (type \"DONE\" to be done" << endl;
cin >> name;
cout << "PLEASE ENTER THE SCHOOL YOU ATTEND:" << endl;
cin >> school;
if(sAtt.find(school)) {//if school is already in list
vector<string> names = sAtt.find(school);
names.push_back(name);
sAtt.erase(school); //erase the old key
sAtt.emplace(school, names); //add key and updated value
} else { //else school is not already in list so add i
vector<string> names;
names.push_back(name);
sAtt.emplace(school, names);
}
}while(!(name == "done"));
sAtt.erase("done");
cout << "HERE ARE THE SCHOOLS ATTENDED ALONG WITH WHO GOES THERE: " << endl;
for (string s: sAtt.keySet()) { //this is the java way of doing it not sure how to do for c++
cout << "\t" << s << sAtt.find(s) << endl;
//should be School: name, name, name, etc. for each school
}
}
【问题讨论】:
-
C++ Loop through Map的可能重复
-
你确定你在
emplace而不是vector<string> names = sAtt.find(school);得到编译器错误吗? emplace 用法对我来说很好。 -
很抱歉,但是通过从 Java 转换代码来学习 C++ 肯定是一件非常头疼的事情。例如,
if(sAtt.find(school))始终为真,无论school和sAtt中的内容是什么。我推荐a good C++ book从基础学习C++。 -
@Yksisarvinen for if 语句将 if(sAtt.count(school)) 代替工作
-
IMO,更多的 C++ -ish 方法是将其与
end迭代器:if(sAtt.find(school) != sAtt.end())进行比较。count会起作用,因为它总是返回 1 或 0,但它看起来很奇怪。
标签: c++