【问题标题】:Implement a map of strings实现字符串映射
【发布时间】:2011-03-06 21:13:59
【问题描述】:

我必须使用二叉搜索树实现一个行为类似于字符串映射的类。这是我实现的类:

template<class T>
class StringMapper {
private:
    // Pair
    struct Pair {
        std::string el1;
        T el2;
    };

    // Nod
    struct Node {
        Pair* data;
        Node* left;
        Node* right;
        Node()
        {
            data = new Pair;
        }
        ~Node()
        {
            delete data;
        }
        int nod_size()
        {
             // code here
        }
    };
    Node* root;
public:
    StringMapper()
    {
        root = 0;
    }
    ~StringMapper() {}
    void insert(std::string from, const T& to)
    {
        // code here
    }

    bool find(std::string from,const T& to) const
    {
        return find(root, to);
    }

    bool find(Node* node, const T& value) const
    {
        // code here
    }

    bool getFirstPair(std::string& from, T& to)
    {
        if(root != 0)
        {
            from = root->data->el1;
            to = root->data->el2;
            return true;
        }
        return false;
    }
    bool getNextPair(std::string& from, T& to)
    {
        if(root != 0)
        {

        }
        return false;
    }

    int size() const
    {
        return root->nod_size();
    }
};

说实话我不知道如何实现函数getNextPair()
如果有人可以帮助我,我将不胜感激。

【问题讨论】:

    标签: c++ data-structures binary-search-tree


    【解决方案1】:

    您的接口是一个内部迭代器。您需要保留某种指向您在迭代中所处位置的指针,并将其设置在 getFirstPair() 中。

    添加后,getNextPair() 将转到下一个。这样做有点困难,但这是你的任务,所以我把它留给你。

    实际的std::map 使用外部迭代器——它将迭代的状态与数据结构分开。主要优点是能够同时进行多次迭代。

    【讨论】:

      【解决方案2】:

      不只是抛出 getNextPair 的算法,你需要保留某种指向“当前”对的内部迭代器。一旦你知道了,为了计算下一对的算法,你自己画一棵有一些节点的树,看看如何在给定树中的任何节点的情况下找到树中的下一个节点。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-10
        • 1970-01-01
        • 1970-01-01
        • 2012-01-23
        • 1970-01-01
        • 2012-08-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多