C ++映射值传递

时间:2014-05-17 12:03:10

标签: c++

这是我试图搜索或显示包含水果数量的整个地图的程序代码。

由于某种原因,搜索功能无效(未返回任何结果),并且代码显示所有数量仅显示地图的最后一个条目。

以下是代码的一些片段。

如果包含更多软件包或语法错误,请忽略,因为我没有将整个代码复制到此处。

使用拼写错误修改并添加了fruit.h

fruit.txt

apple
02
orange
06
pear
03
lemon
07

从main.cpp读取并提示输入任务选择。

#include <string>
#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
#include <cstdlib>
#include <algorithm>
#include "fruit.h"

using namespace std;

int main()
{
    void readFile(); //read file    
    readFile();

    void perform(int); //case selection
    int caseInput;

    cout << "Press 1 for search" << endl;
    cout << "Press 2 to show all" << endl;
    cout << "choice: ";

    cin >> caseInput;
    perform(caseInput);
}

void readFile() //read line and pass to fruit.cpp using vector
{
    vector<fruit> fruitVector;
    string fruitName;
    int quantity;
    ifstream file;
    txt.open("fruit.txt");
    while (!txt.eof())
    {
        getline(txt, fruitName);
        getline(txt, quantity);
        fruitVector.push_back(fruit(fruitName, quantity));
    }
    txt.close();
}

void perform(int caseInput)
{
    string searchTerm;
    switch (caseInput)
    {
        case 1: // search function
        {
            cout << "input: ";
            cin >> searchTerm;
            taskOne(searchTerm);
            break;
        }
        case 2:
        {
            tasktwo(); // not done yet, but nvm
            break;
        }
    }
}

这是我的fruit.cpp

#include <string>
#include <map>
#include <iostream>
#include <cctype>
#include "fruit.h"

using namespace std;

fruit::fruit(string fruitName, int quantity)
{
    fruitMap[fruitName] = quantity; //storing vectors to map
    passMap(fruitMap); //pass the map to task.cpp
};

这是我的task.cpp

#include <cstdlib>
#include <iostream>
#include <string>
#include <map>

using namespace std;

map<string, int> fruitMap;

void passMap(map<string, int>input)
{
    fruitMap = input;
}
void taskOne(string searchTerm)
{
    auto it = fruitMap.find(searchTerm);
    if(it != fruitMap.end())
    {
        cout << "output = " << endl;
        cout << it->second << endl; // should print out the quantity of fruit
    }
    //in fact i try output the whole map using the code:
    //
    //for (auto it = fruitMap.begin(); it != fruitMap.end(); ++it)
    //{
    //    cout << it->first << " " << it->second << "\n";
    //}
    //
    //but it only output the last line which is:
    //lemon 07
}

fruit.h

#include <string>
#include <map>
#include "task.h"

class fruit{
private:
    std::string fruitName;
    std::int quantity;
    std::map<std::string, int> fruitMap;
public:
    fruit(std:string, int);
}

1 个答案:

答案 0 :(得分:0)

每个水果都有自己的地图存放。你需要一张普通水果的地图。你可以通过使fruitMap静态来实现这一点,或者更好地从水果中完全分离地图并传递对函数的引用