如何访问映射的向量(整数和字符串的向量)

how to access vector of map of ( int and vector of strings )

本文关键字:向量 整数 字符串 何访问 映射 访问      更新时间:2023-10-16

如何在passed_vector函数中访问整数映射和字符串向量。我只想在该函数中打印它们。

#include <iostream>
#include <vector>
#include <map>
#include <string>
using namespace std; 
typedef vector< map< int, vector<string> > > vmis;
typedef map< int, vector<string> > mis;
typedef vector<string> vstr;
void passing_vector(const vmis &meetings);
//return size of vector
template< typename A >  size_t n_elements( const A& a )
{
   return sizeof a / sizeof a[ 0 ];
}
int main()
{
    vmis meeting_info;
    mis meeting_members;
    vstr sw_vec;
    vstr sys_vec;
    string sw_team[] = {"Ricky", "John", "David"};
    string sys_team[] = {"Simmon", "Brad", "Schmidt", "Fizio"};
    sw_vec.insert(sw_vec.begin(), sw_team, sw_team + n_elements(sw_team) );
    sys_vec.insert(sys_vec.begin(), sys_team, sys_team + n_elements(sys_team) );
    meeting_members.insert(make_pair(520, sw_vec));
    meeting_members.insert(make_pair(440, sys_vec));
    meeting_info.push_back(meeting_members);
    passing_vector(meeting_info);
    return 0;
}
void passing_vector(const vmis &meetings)
{
    vmis::iterator itvmis = meetings.begin();
    //how do i access map of int and vectors of string.
    //I just want to print them.

}

我知道如何在主函数中打印它们。

vmis::iterator itvims = meeting_info.begin();
for( int i = 0; i < meeting_info.size(); i++ )
{
    mis::iterator itm = meeting_members.begin();
    for(itm; itm != meeting_members.end(); itm++ )
    {
       cout << itm->first << " : ";
       vstr::iterator it = itm->second.begin();
       for(it; it != itm->second.end(); it++)
           cout << *it << " ";
       cout << endl;
    }
}

期望的输出440 : 西蒙·布拉德·施密特·菲齐奥520:瑞奇·约翰·大卫

如果有更好的方法,建议总是受欢迎的。

最简单的方法是使用 auto ,也因为你的meetings是 const 的,你需要使用 const_iterator

void passing_vector(const vmis &meetings)
{
  vmis::const_iterator itvims = meetings.begin();
  //how do i access map of int and vectors of string.
  //I just want to print them.
  for (;itvims != meetings.end(); ++itvims)
  {
    const auto& map_item = *itvims;
    for (const auto& map_it : map_item)
    {
      int map_key = map_it.first;
      const auto& str_vec = map_it.second;
      for (const auto& str : str_vec)
      {
        std::cout << map_key << " - " << str << "n";
      }
    }
  }
}

[编辑]

C++98 版本:

void passing_vector(const vmis &meetings)
{
  vmis::const_iterator itvims = meetings.begin();
  //how do i access map of int and vectors of string.
  //I just want to print them.
  for (;itvims != meetings.end(); ++itvims)
  {
    const mis& map_item = *itvims;
    for (mis::const_iterator map_it = map_item.begin(); map_it != map_item.end(); ++map_it)
    {
      int map_key = map_it->first;
      const vstr& str_vec = map_it->second;
      for (vstr::const_iterator sitr = str_vec.begin(); sitr != str_vec.end(); ++sitr)
      {
        std::cout << map_key << " - " << *sitr << "n";
      }
    }
  }
}