I have written a class to wrap around an std::map
, along with an iterator class to allow controlling accessing the map
's key:
#include <map>
class Container
{
public:
class iterator
{
using map = std::map < int, int >;
map::const_iterator _iter;
public:
iterator() {}
iterator(map::iterator iter) :_iter(iter) {}
iterator(map::const_iterator iter) :_iter(iter) {}
iterator(const iterator& b) :_iter(b._iter) {}
iterator& operator=(const iterator& b)
{
_iter = b._iter;
return *this;
}
iterator& operator++()
{
++_iter;
return *this;
}
iterator operator++(int)
{
return iterator(_iter++);
}
const map::key_type first()
{
return std::abs(_iter->first);
}
const int second()
{
return _iter->second;
}
bool operator==(const iterator& b)
{
return _iter == b._iter;
}
bool operator!=(const iterator& b)
{
return _iter != b._iter;
}
};
void insert(int key, int value)
{
_map[-key] = value; // Key is modified from user, hence need for wrapper
}
iterator begin()
{
return iterator(_map.begin());
}
iterator end()
{
return iterator(_map.end());
}
iterator find(int key)
{
return iterator(_map.find(key));
}
iterator erase(iterator iter)
{
return iterator(_map.erase(iter));
}
private:
std::map<int, int> _map;
};
My required operations are:
- Iterating
- Finding
- Erasing
- Getting key
- Getting value
I would like usage to be like:
int main()
{
Container o;
o.insert(-1, 100);
o.insert(-2, 200);
o.insert(-3, 300);
o.insert(-4, 300);
for (Container::iterator i = o.begin(); i != o.end();)
{
if (i.first() == -2)
{
std::cout << i.first() << " " << i.second() << std::endl;
++i;
}
else
{
i = o.erase(i);
}
}
}
so that I can erase elements and continue iterating.
However, I am struggling to implement the container's erase()
method because the input is my custom iterator
type, not the map's key_type
.