mardi 24 novembre 2020

How do I implement a begin() member function in my custom data structure?

I'm trying to create my own data-structure that can determine if a value is an element within it in O(1) time with a hash-map.

I'm working on adding more member functions so that it's more similar to the STL containers. Here's what I currently have that's relevant to the problem:

template <class T>
class setfind {

private:
    long long _size = 0;
    unordered_map<T, bool> _set;

public:
    // constructors
    setfind() {}
    // initialize from some iterable
    template <class InputIterator>
    setfind(InputIterator beg, InputIterator en){
        _size = en - beg;
        while (beg != en){
            _set[*beg] = true;
            beg++;
        }
    }

    bool contains(const T &val){
        return _set[val];
    }
    bool contains(const T &&val){
        return _set[val];
    }
};

As you can see, its core is the unordered_map. I want to write a member function that returns a begin iterator to the _set variable. I tried putting this in:

template <class InputIterator>
InputIterator begin()
{
    return _set.begin();
}

but that led to a compilation error saying that there was no matching member function. I don't know enough about iterators and template-classes to fix this. Does anyone know how to implement it or what's wrong? Are there any good resources so that I can learn more about this?

Also some optimization tips for this class would be appreciated because this is going to be used under a time-limit.

EDIT: I’m restricted to using c++11 EDIT2: Fixed a bug in the constructor

Aucun commentaire:

Enregistrer un commentaire