vendredi 31 août 2018

How to merge two functions with same conditions?

I quickly wrote the below class for this question.

I'm looking for a way to merge addFruit() with removeFruit().

They both use identical conditions but just different function call at the end.

My Code :

#include <iostream>
#include <string>
#include <vector>

class MyClass
{
public:
    void addFruit(const std::string &str, int count)
    {
        if (str == "apples")
            addToVec(apples, count);
        else if (str == "oranges")
            addToVec(apples, count);
        else if (str == "lemons")
            addToVec(apples, count);
        else if (str == "melons")
            addToVec(apples, count);
        else if (str == "bananas")
            addToVec(apples, count);
        else
            std::cout << "Unknown Fruit : " << str << '\n';
    }
    void removeFruit(const std::string &str)
    {
        if (str == "apples")
            removeFromVec(apples);
        else if (str == "oranges")
            removeFromVec(apples);
        else if (str == "lemons")
            removeFromVec(apples);
        else if (str == "melons")
            removeFromVec(apples);
        else if (str == "bananas")
            removeFromVec(apples);
        else
            std::cout << "Unknown Fruit : " << str << '\n';
    }
private:
    void addToVec(std::vector<int> &vec, int count)
    {
        vec.push_back(count);
    }
    void removeFromVec(std::vector<int> &vec)
    {
        vec.pop_back();
    }
    std::vector<int> apples;
    std::vector<int> oranges;
    std::vector<int> lemons;
    std::vector<int> melons;
    std::vector<int> bananas;
};

Any clever way to nicely merge the two functions?

Aucun commentaire:

Enregistrer un commentaire