gpt4 book ai didi

c++ - 如何在控制台的三个不同列中一起打印三张 map ? C++

转载 作者:行者123 更新时间:2023-11-30 03:53:58 26 4
gpt4 key购买 nike

我有三个map<string,int>实例。这三个都包含学生姓名和他们的分数。第一张 map 包含计算机专业的学生,​​第二张 map 包含医学生,第三张包含商科学生。我知道我必须使用 <iomanip>图书馆和setw .我不明白的是如何同时遍历所有三个以将它们一起打印?谁能帮忙?我希望它在控制台上打印为:

COMPUTER MEDICAL COMMERCE
joey 45 ed 20 harold 50
malisa 36 jane 60 aron 70
emily 60 judy 70 barney 45

到目前为止,我所拥有的只是一张接一张地打印 map

  map<string,int> ::const_iterator it;
cout<<endl;
cout<<setw(36)<<"COMPUTER STUDENTS"<<endl;
for( it = one.begin(); it != one.end(); ++it)
{
cout <<setw(20)<<it->first;
cout <<setw(5)<<it->second<<endl;
}
cout<<setw(36)<<"MEDICAL STUDENTS"<<endl;
for( it = two.begin(); it != two.end(); ++it)
{
cout <<setw(20)<<it->first;
cout <<setw(5)<<it->second<<endl;
}
cout<<setw(36)<<"COMMERCE STUDENTS"<<endl;
for(it = three.begin(); it != three.end(); ++it)
{
cout <<setw(20)<<it->first;
cout <<setw(5)<< it->second<<endl;
}`

最佳答案

对第一个 map 使用范围循环,对接下来的两个 map 使用迭代器:

 std::map<string,int> one, two, three;
//You inserted records to all three maps
std::map<string,int>::iterator it2 = two.begin();
std::map<string,int>::iterator it3 = three.begin();

if( one.size()== two.size() && two.size()== three.size())
{
for( auto &x : one)
{
std::cout<<setw(20)<< x.first;
std::cout<<setw(5)<< x.second;
std::cout<<setw(20)<<it2->first;
std::cout<<setw(5)<< it2->second;
std::cout<<setw(20)<<it3->first;
std::cout<<setw(5)<< it3->second;
++it2;
++it3;
}

}

关于c++ - 如何在控制台的三个不同列中一起打印三张 map ? C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29826160/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com