c++ - C++ 创建一个以字符串为键、字符串向量为值的映射
问题描述
此代码提示用户询问他们的姓名和他们就读的学校。将两者都存储到地图中(将名称存储到向量中)。然后,我想以这种格式打印出学校和每个就读该学校的人的姓名。
学校:名字,名字,名字。/new line School : name, name , name etc. . . .
我第一次在 java 中做,并试图转换为 c++,不确定我是否正确执行此操作,也不确定如何将底部的 for 循环转换为 c++(在 c++ 中是否有类似于 map.keySet() 的东西? )
我不断收到 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++ 从头开始编码的东西,而不是简单地尝试从 Java 中逐行翻译。想想你想做什么,而不是如何复制 Java。
例如,下面的代码片段应该做什么?
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);
}
您可以逐行解释这一点,但整个过程是添加name
到与 关联的向量的末尾,并school
在需要时创建该向量。现在来看看。它返回(引用)与给定键关联的值,并在需要时创建该值。因此,执行上述操作的更简单方法是:std::map::operator
[]
sAtt[school].push_back(name);
一行,尝试将迭代器转换为布尔值或值类型没有问题。
至于从地图中获取值,您将遍历地图,而不是构造一组帮助值并遍历它。起点(不完全是您想要的)是:
for ( auto & mapping : sAtt ) { // Loop through all school -> vector pairs, naming each pair "mapping".
cout << mapping.first << ":"; // The first element in the pair is the school name.
for ( auto & name : mapping.second ) // Loop through the associated vector of names.
cout << '\t' << name; // Using tabs instead of commas.
cout << endl; // End the school's line.
}
基本上,您应该记住 astd::map
包含对,.first
作为键和.second
作为值。
推荐阅读
- python - 如何在给定特征值的情况下找到特征向量
- python - 如何在基因组数据框中插入互补碱基?
- python - Regular expression exclude matches surrounded by quotation marks and lines starting with %
- ruby-on-rails - Ruby on Rails Flash 通知无法正常工作
- excel - Excel:对范围内的公式使用averageif
- amazon-cloudfront - 如何检查 AWS Cloudfront CNAME 是否有效?
- python - CodeBuild 仍在通过测试阶段
- python - 汇总数据框中的事务链,由列值链接的行
- android - Android中的Onchange电话语言我的应用程序布局更改
- jenkins - Jenkins - 无法从 Jenkinsfile 运行管道