Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map template class

I am just confused as to what my file is supposed to look like. I am not sure on the syntax as well as how to read in the array.

like image 583
12345678 Avatar asked Feb 27 '26 16:02

12345678


1 Answers

I'm just confused as to what my Map.cpp file is supposed to look like.

  • First of all, you can not write your template class implementation in a .cpp file. It should be all in a header file. Read the following for more info. Why can templates only be implemented in the header file?
  • Secondly, there is no constructor declaration in your Map class which takes std::string as a parameter. Provide one!
    template <typename Domain, typename Range>
    class Map
    {
    public:  
     Map(const std::string& filename);  // declare one constructor which takes std::string
        // ... other members
    };
    
  • Thirdly, your member function definitions missing the template parameters.

    template <typename Domain, typename Range>  // ---> this
    void Map<Domain, Range>::add(Domain d, Range r)
    {
     // implementation
    }
    
    template <typename Domain, typename Range>  // ---> this
    bool Map<Domain, Range>::lookup(Domain d, Range& r)
    {
     // implementation
    }
    
  • Last but not the least, you are missing a proper destructor, which is essential for the Map class, as the allocated memory(using new) should be freed. Therefore, do accordingly the The rule of three/five/zero.

That being said, if you could have used std::vector, the manual memory management could be avoided.

#include <vector>

template <typename Domain, typename Range>
class Map
{
public:
    //...
private:
    // other members
    std::vector<Domain> dArray;
    std::vector<Range> rArray;
};

As a side note, avoid practising with using namespace std;. Why is "using namespace std;" considered bad practice?

like image 67
JeJo Avatar answered Mar 02 '26 04:03

JeJo