c++ - 使用 map 为类创建迭代器

标签 c++

我正在使用 map 实现一个类,如下所示:

class Letras {
    typedef std::pair<int, int> p_c;
    std::map<char, p_c> bolsa;
public:
    ...
};

我想实现一个迭代器的功能,像这样使用:

Letras l;

Letras::iterator it;
for ( it = l.begin(); it != l.end(); ++it )
    cout << *it << endl;

因此它从 std::map 第一个组件(键)中打印出 char

提前致谢。

关于 Letras 的更多信息

Letras 是一个实现类 Scrubble 字母集的类,map 用于表示一组 letras (字母(西类牙语),如下所示:

{{letter_1, {quantity_1, score_1}}, {letter_2, {quantity_2, score_2}}, ..., {letter_n, {quantity_n, score_n}}}

其中 letter_i 是集合中的某个字母,quantity_i 是该字母在集合中的次数(一个类似 Scrubble 的字母集合可以有各种相同的letters),score_i 是字母得分。

我使用了一个映射,因为一个字母只能有一个关联的分数,所以在这个类中,i != j => letter_i != letter_j

Letras 的用途是从 Diccionario 类(dictionary)中找到由特定字母集组成的最佳单词,另一个类实现了用于快速搜索和查找的 DAWG 结构。

最佳答案

你可以这样做:

#include <iostream>
#include <map>
#include <algorithm>

using namespace std;

class Letras {
private:
    typedef std::pair<int, int> p_c;
    std::map<char, p_c> bolsa;

public:
    class iterator {
    private:
        std::map<char, p_c>::iterator it;

    public:
        iterator(const std::map<char, p_c>::iterator &it) {
            this->it = it;
        }

        // EDIT: Removing Copy Semantics
        iterator(const iterator &it) = delete;
        iterator &operator =(const iterator &it) = delete;

        // EDIT: Enabling Move Semantics
        iterator(iterator &&it) = default;
        iterator &operator =(iterator &&it) = default;

        auto &operator *() const {
            return it->first;
        }

        iterator &operator ++(int) {
            this->it++;
            return *this;
        }

        bool operator !=(const iterator &it) {
            return this->it != it.it;
        }
    };

    auto begin() {
        return iterator(bolsa.begin());
    }

    auto end() {
        return iterator(bolsa.end());
    }

    void insert(const std::pair<char, p_c> &p) {
        bolsa.insert(p);
    }
};

int main() {
    Letras b;
    b.insert(make_pair('f', make_pair(1, 2)));
    b.insert(make_pair('g', make_pair(1, 2)));
    b.insert(make_pair('h', make_pair(1, 2)));

    for (auto it = b.begin(); it != b.end(); it++) {
        cout << *it << endl;
    }

    return 0;
}

关于c++ - 使用 map 为类创建迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54032043/

相关文章:

c++ - glGenBuffers - 释放内存?

c++ - SFML:如何解决在 sfml 中旋转 Sprite 时 Sprite 质量下降的问题

c++ - 长12位数字?

C++链表复制和克隆函数

c++ - 无法在程序中指定文件路径前缀

c++ - Doxygen 仅支持 STL 容器中的自定义类

c++ - 二叉存储树 fstream 出错

c++ - 如何在 C++ 中组合两个或多个任意类型的 vector

c++ - 简单的引用变量赋值导致全局指针中的段错误?

c++ - 数组中对象的范围