首页 > 解决方案 > 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++

解决方案


这段代码应该会出现很多错误。总的来说,这个项目看起来应该是你应该用 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作为值。


推荐阅读