如何在控制台上将三张地图一起打印成三个不同的列?C++



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

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

到目前为止,我拥有什么,但这只是打印一张又一张地图

  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;
  }`

对第一个映射使用范围循环,对接下来的 2 个映射使用迭代器:

 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;
    }
  }

由于大小保证相等(根据您的评论),因此您可以使用一个循环和三个迭代器,类似于以下内容。请注意,cout报表应根据您的需要安排。这只是为了展示一个示例,说明如何在单个循环中迭代三组大小相等的集合:

map<string,int> ::const_iterator it1, it2, it3;
it1=one.begin();
it2=two.begin();
it3=three.begin();
while(it1!=one.end())
{
    cout<<it1->first<<" ";  // You should format them based on your need
    cout<<it1->second<<" "; // This is just an example.
    cout<<it2->first<<" ";
    cout<<it2->second<<" ";
    cout<<it3->first<<" ";
    cout<<it3->second<<" ";
    it1++; it2++; it3++;
}

我有一个想法,不需要大小相等的假设。将三个地图的内容放入一个公共向量中:

#include <iostream> 
#include <vector>
#include <map>
#include <algorithm>
using namespace std;
int main()
{
 map<int, int> m;
 m[1] = 1;
 m[2] = 2;
 map<int, int> n;
 n[3] = 3;
 n[4] = 4;
vector<pair<int, int> > v;
copy(m.begin(), m.end(), back_inserter(v));
copy(n.begin(), n.end(), back_inserter(v));
for(int i = 0; i < v.size(); ++i)
cout << v[i].first << " : " << v[i].second << endl;
}

这会消耗额外的内存。但好的一点是,您可以通过向量中的任何算法(例如排序)对这些数据做任何您想做的事情。我不知道为什么你需要三张地图。我的偏好是为数据添加一个额外的标志,并将它们放在一张地图中。

最新更新