映射迭代器问题。代码包括在内

时间:2013-08-01 00:07:19

标签: c++ map iterator

所以这里是我的所有代码,我真的不明白为什么我会收到这些错误。 问题在于导出配方功能。

#include<iostream>
#include<fstream>
#include<map>
#include<vector>
#include<string>


using namespace std;

void DisplayMenu();
void AddRecipe( map< string, vector<string> >& recipes );
void ExportRecipes( map< string, vector<string> >& recipes );

int main ( void ){

   int choice = 0;
   bool done = false;
   map< string, vector<string> > recipes;

    while ( done == false ){
       DisplayMenu();
       cin >> choice;

       if ( choice == 3 ){
        done = true;
       }
       else if ( choice == 2 ){
        ExportRecipes( recipes );
       }
       else if ( choice == 1 ){
        AddRecipe( recipes );
       }

    }
}

void DisplayMenu(){ 
   cout << "1. Add Recipe " << endl;
   cout << "2. Export Recipes " << endl;
   cout << "3. Exit" << endl;
}

void AddRecipe( map< string, vector<string> >& recipes ){

   string name, ingredient;
   bool done = false;
   cout << "Enter recipe name: ";
   cin >> name;
   while ( done == false ){     
       cout  << "Enter new ingredient and amount( enter done to exit )" << endl;
       getline( cin , ingredient, '\n' );

       if ( ingredient == "done" ){
           done = true;
       }

       if( ingredient != "done"){
           recipes[ name ].push_back( ingredient );
           cout << "Added \"" << ingredient << "\"." << endl << endl;
       }        
   }
}


void ExportRecipes(  map< string, vector<string> >&recipes ){

   ofstream outFile;
   outFile.open( "Recipes.txt" );

   for ( map< string, vector<string> >::iterator recipe =
       recipes.begin(); recipe != recipes.end(); recipe++ ) {
       outFile << endl << endl << recipe -> first << endl;

       for ( map< string, vector<string> >::iterator ingredients = 
           recipe->second.begin(); ingredients != recipe->second.end();
            ingredients++ ) {
               outFile << "\t" << *ingredients << endl;
       }
   }
}

如果我只在导出中迭代第一个for循环,我可以得到密钥,但我无法获得该值。

2 个答案:

答案 0 :(得分:1)

for ( map< string, vector<string> >::iterator ingredients = 
        recipe->second.begin();

recipe->secondvector<string>。因此,recipe->second.begin()会返回vector<string>::iterator,而不是map< string, vector<string> >::iterator

答案 1 :(得分:1)

为什么你有第二个for循环用Map。 recipe-&gt; second是一个矢量,所以试试这个 -

void ExportRecipes(  map< string, vector<string> >&recipes ){
   ofstream outFile;
   outFile.open( "Recipes.txt" );

   for ( map< string, vector<string> >::iterator recipe =
       recipes.begin();
        recipe != recipes.end();
        recipe++ )
   {
      outFile << endl << endl << recipe -> first << endl;

      for ( vector<string>::iterator ingredients = 
        recipe->second.begin();
            ingredients != recipe->second.end();
            ingredients++ )
        {
            outFile << "\t" << *ingredients << endl;
        }

   }
 }