如何访问(int和字符串向量)

时间:2016-05-30 17:46:13

标签: c++ vector stl

如何在pass_vector函数中访问int的map和string的向量。 我只是想在那个函数中打印它们。

#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.


}

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

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:Simmon Brad Schmidt Fizio 520:Ricky John David

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

1 个答案:

答案 0 :(得分:1)

最简单的方法是使用auto,因为您的meetings是常量,您需要使用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";
      }
    }
  }
}