簡體   English   中英

使用地圖為類創建迭代器

[英]Create iterator for class using map

我正在使用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是該字母在集合中的次數(類似雜亂的字母集合可以具有各種相同的字母),而score_i是字母分數。

我使用了地圖,因為字母只能具有關聯的分數,因此在此類中, i != j => letter_i != letter_j

Letras的實用程序是從Diccionario類( 字典 )中找到由某個字母集形成的最佳單詞,該類已經實現了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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM