mianfg
mianfg

Reputation: 15

Create iterator for class using map

I am implementing a class using a map, like so:

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

And I'd like to implement the functionality of an iterator, to be used like so:

Letras l;

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

So that it prints out the chars from the std::map first component (key).

Thanks in advance.

More information about Letras

Letras is a class that implements a Scrubble-like letter set, the map is used to represent a set of letras (letters in Spanish) like the following:

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

Where letter_i is a certain letter from the set, quantity_i is the amount of times that letter is in the set (a Scrubble-like letter set can have various identical letters) and score_i is the letter score.

I have used a map because a letter can only have an associated score, so that in this class, i != j => letter_i != letter_j.

The utility of Letras is to find the best words formed by a certain letter set from a Diccionario class (dictionary), another class that has implemented a DAWG structure for fast search and lookup.

Upvotes: 0

Views: 75

Answers (1)

Kunal Puri
Kunal Puri

Reputation: 3427

You can do something like this:

#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;
}

Upvotes: 2

Related Questions