Displaying objects of custom templated abstract data type

124 Views Asked by At

I am developing an abstract data type that is similar to the map STL for an assignment. The brief says I should provide a range of facilities, including outputting objects contained in the abstract data type. How would I go about outputting an array data stored in the ADT, I can't use any STL so I presume I can't use iterators, and having a function that uses cout in the ADT seems silly. Any suggestions? Thanks. Code below:

template <typename K, typename D>
class Map
{
private:
int mapSize;
int dataFilled;
struct keyData
{
    K key;
    D data;
};

keyData* datas;
keyData* ptr;
1

There are 1 best solutions below

1
On

If you go the way of letting the user access the objects, then I would go with iterators and operator[]. To define iterators you simply need to define a begin and end member function (with eventual const overloads). The problem is that you generally want to offer both keys and values of the map. The way std::map solves this is by returning some type that is semantically equivalent to a pointer to std::pair<const Key, T> so that you can access the key via std::get<0>(*it) and the value by std::get<1>(*it).

If you want to define a custom "print" function you can simply define operator<< for std::ostream:

template<class Key, class Value>
std::ostream& operator<<(std::ostream& os, const Map<Key, Value>&) { ... }

This way you'll be able to use:

Map<Key, Value> map;
std::cout << map;

I'd recommend providing, in a similar fashion, also an operator>> for std::istream.

For more inspiration you can take a look at the std::map interface.