Question

NO VECTORS PLEASE Start a simple Matrix template class In this lab, you’ll be writing a...

NO VECTORS PLEASE

Start a simple Matrix template class

In this lab, you’ll be writing a template class to represent a matrix. Because it’s a template, your matrix class will be able to work with different types of underlying data.

Start by creating a new file matrix.hpp. Inside this file, start to write your matrix template class. Here’s a start for the class definition:

template <class T>
class Matrix {
private:
  int _rows;
  int _cols;
  T** data;
public:
  Matrix(int rows, int cols);
  ~Matrix();
  int rows();
  int cols();
  T& at(int row, int col);
};

Here, the constructor should allocate the data field so that it contains the specified number of rows and columns, and the destructor should free the memory allocated to the data field (in addition to anything else you need to do in the destructor). In addition to the constructor and destructor, you should write accessors to return the number of rows and the number of columns.

You should also write an at() method that returns a reference to the data element at a specified location. By returning a reference, you can use the at() method to set values in a matrix as well as access them. The at() method should throw an std::out_of_range exception if either the specified row or the specified column is outside the bounds of the matrix.

Remember, all of the methods for a template class need to be implemented directly in the header file itself.

Once you have your Matrix class looking good, create a new file application.cpp. In this file, write a small application to test your Matrix class. Create a few Matrix objects containing different data types, like int, float, and double. Fill those Matrix objects with values using loops and the at() method, and print out some values from the matrices to make sure they look like what you expect. Try to access some values outside the bounds of your matrices to make sure an exception is thrown.

Make sure to add and commit your files to your git repository and push them to GitHub.

Step 3: Implement an add() method to add two matrices

Add a new method add() to your Matrix template class to add two Matrix objects. The declaration of this method inside your class definition should look like this:

void add(const Matrix<T>& other);

Importantly, note that the Matrix argument to your add() method will also be of the same type T. The add() method should simply take the value at each location in other and add it to the value at the corresponding location of the Matrixobject represented by this, replacing the latter with the sum of the two values.

Make sure to augment your application to test your add() method, commit your changes to your git repository, and push them to GitHub when everything is working.

Step 4: Write a size_mismatch exception and throw it in add()

One major catch about adding two matrices is that they must have the same dimensions. Otherwise, it’s not possible to add them. Your Matrix class should not allow the user to pass an argument other to the add() method that has different dimensions than the Matrix object represented by this. To do this, you should create a new file size_mismatch.hpp and, in it, write a new exception class called size_mismatch. This class should be derived from the std::exception class. Remember, at a minimum, a new class that derives from std::exception must implement the following method:

virtual const char* what() const throw();

However, you may implement any additional methods that help you make an informative exception (e.g. a new parameterized constructor). You may also add new private data members if needed. You may place the implementations of the class methods for size_mismatch directly in the class definition in size_mismatch.hpp, or you may create a new file size_mismatch.cpp in which to place these implementations.

Once you have your size_mismatch class written, augment your Matrix class’s add() method to throw a size_mismatchwhenever the other argument has different dimensions than the Matrix object represented by this.

0 0
Add a comment Improve this question Transcribed image text
Answer #1
#pragma once

#include <vector>
#include <exception>
#include <iosfwd>

template <typename T>
class Matrix
{
    std::vector<std::vector<T>> matrix;
    size_t rowCount;
    size_t columnCount;
public:
    Matrix(size_t rowCount_, size_t columnCount_):
        matrix(rowCount_), 
        rowCount(rowCount_), 
        columnCount(columnCount_)
    {
        for (auto& row : matrix)
        {
            row.resize(columnCount);
            for (auto& cell : row)
            {
                cell = 0;
            }
        }
    }

    Matrix(size_t rowCount_, size_t columnCount_, const T& value) :
        matrix(rowCount_),
        rowCount(rowCount_),
        columnCount(columnCount_)
    {
        for (auto& row : matrix)
        {
            row.resize(columnCount, value);
        }
    }

    Matrix(const Matrix& other) = default;

    Matrix(Matrix&& other) :
        matrix(std::move(other.matrix))
    {
        rowCount = other.rowCount;
        columnCount = other.columnCount;
    }

    Matrix& operator=(const Matrix& other) = default;

    Matrix& operator=(Matrix&& other)
    {
        std::swap(matrix, other.matrix);
        rowCount = other.rowCount;
        columnCount = other.columnCount;
        return *this;
    }

    Matrix& operator*=(const T& rhs)
    {
        for (auto& row : matrix)
        {
            for (auto& cell : row)
            {
                cell *= rhs;
            }
        }
        return *this;
    }

    Matrix& operator*=(const Matrix& rhs)
    {
        if (columnCount != rhs.rowCount)
        {
            throw std::logic_error("column count of lhs and row count of rhs are not equal\n");
        }

        Matrix temp(rowCount, rhs.columnCount);

        for (size_t i = 0; i < temp.rowCount; i++)
        {
            for (size_t j = 0; j < temp.columnCount; j++)
            {
                for (size_t k = 0; k < columnCount; k++)
                {
                    temp[i][j] += matrix[i][k] * rhs[j][k];
                }
            }
        }
        std::swap(matrix, temp.matrix);

        return *this;
    }

    Matrix& operator+=(const Matrix& rhs)
    {
        if (rowCount != rhs.rowCount || columnCount != rhs.columnCount)
        {
            throw std::logic_error("either or both of row count and column count of lhs and rhs are not equal\n");
        }

        for (size_t i = 0; i < rowCount; i++)
        {
            for (size_t j = 0; j < columnCount; j++)
            {
                matrix[i][j] += rhs[i][j];
            }
        }

        return *this;
    }
    size_t rows()
    {
        return rowCount;
    }

    size_t columns()
    {
        return columnCount;
    }

    const size_t rows() const
    {
        return rowCount;
    }

    const size_t columns() const
    {
        return columnCount;
    }

    std::vector<T>& operator[](size_t row)
    {
        return matrix[row];
    }

    const std::vector<T>& operator[](size_t row) const
    {
        return matrix[row];
    }
};

template <typename T>
bool operator==(const Matrix<T>& lhs, const Matrix<T>& rhs)
{
    if (lhs.rows() != rhs.rows() || lhs.columns() != rhs.columns())
    {
        return false;
    }

    for (int i = 0; i < lhs.rows(); i++)
    {
        for (int j = 0; j < lhs.columns(); j++)
        {
            if (lhs[i][j] != rhs[i][j])
            {
                return false;
            }
        }
    }
    return true;
}

template <typename T>
bool operator!=(const Matrix<T>& lhs, const Matrix<T>& rhs)
{
    return !(lhs == rhs);
}

template <typename T>
Matrix<T> operator+(Matrix<T> lhs, const Matrix<T>& rhs)
{
    return lhs += rhs;
}

template <typename T>
Matrix<T> operator*(Matrix<T> lhs, const Matrix<T>& rhs)
{
    return lhs *= rhs;
}

template <typename T>
Matrix<T> operator*(Matrix<T> lhs, const T& rhs)
{
    return lhs *= rhs;
}

template <typename T>
Matrix<T> operator*(const T& lhs, Matrix<T> rhs)
{
    return rhs *= lhs;
}

template <typename T>
std::istream& operator >> (std::istream& is, Matrix<T>& matrix)
{
    for (size_t i = 0; i < matrix.rows(); i++)
    {
        for (size_t j = 0; j < matrix.columns(); j++)
        {
            is >> matrix[i][j];
        }
    }

    return is;
}

template <typename T>
std::ostream& operator<< (std::ostream& os, const Matrix<T>& matrix)
{
    for (size_t i = 0; i < matrix.rows(); i++)
    {
        for (size_t j = 0; j < matrix.columns(); j++)
        {
            os << matrix[i][j] << ' ';
        }
        os << "\n";
    }

    return os;
}
Add a comment
Know the answer?
Add Answer to:
NO VECTORS PLEASE Start a simple Matrix template class In this lab, you’ll be writing a...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Binary Tree Template Write your own version of a class template that will create a binary...

    Binary Tree Template Write your own version of a class template that will create a binary tree that can hold values of any data type. Demonstrate the class with a driver program. Place your binary tree template in it's own header file, Btree.h. Include methods for the following: inserting new values into the tree removing nodes from the tree searching the tree returning the number of nodes in the tree displaying the contents of the tree using preorder traversal Your...

  • In this assignment, you are asked to: 1. create a Matrix class that stores and operate...

    In this assignment, you are asked to: 1. create a Matrix class that stores and operate on a dynamic two-dimensional array. The class has the following structure: Private member variables: - int ** mat; - int rows; - int cols; Public member functions: +Default constructor: sets both rows and cols to 3 and creates 3x3 matrix dynamically +Parameterized constructor: sets the rows and cols to the values passed to the constructor and create a matrix with the given dimensions. +Destructor:...

  • in c++ please include all of the following " template class, template function, singly linked list,...

    in c++ please include all of the following " template class, template function, singly linked list, the ADT stack, copy constructor, operator overloading, "try catch"and pointers Modify the code named "Stack using a Singly Linked List" to make the ADT Stack that is a template class has the code of the destructor in which each node is directly deleted without using any member function. As each node is deleted, the destructor displays the address of the node that is being...

  • Need C++ coding for this lab exercise given below :) 4. Lab Exercise — Templates Exercise...

    Need C++ coding for this lab exercise given below :) 4. Lab Exercise — Templates Exercise 1 - Function Templating For this part of the lab make a template out of the myMax function and test it on different data types. Copy maxTemplate.cpp to your Hercules account space. Do that by: Entering the command:cp /net/data/ftp/pub/class/115/ftp/cpp/Templates/maxTemplate.cpp maxTemplate.cpp Compile and run the program to see how it works. Make a template out of myMax. Don't forget the return type. Modify the prototype appropriately. Test your myMax template on int, double,...

  • Please help me out with this assignment. Please read the requirements carefully. And in the main...

    Please help me out with this assignment. Please read the requirements carefully. And in the main function please cout the matrix done by different operations! Thanks a lot! For this homework exercise you will be exploring the implementation of matrix multiplication using C++ There are third party libraries that provide matrix multiplication, but for this homework you will be implementing your own class object and overloading some C+ operators to achieve matrix multiplication. 1. 10pts] Create a custom class called...

  • please write the code in C++ 2 Base class File 3 Derived class PDF 3.1 Class...

    please write the code in C++ 2 Base class File 3 Derived class PDF 3.1 Class declaration • The class PDF inherits from File and is a non-abstract class 1. Hence objects of the class PDF can be instantiated. 2. To do so, we must override the pure virtual function clone) in the base class • The class declaration is given below. • The complete class declaration is given below, copy and paste it into your file. . It is...

  • C++,please help. I have no idea how to do that begining with zero parameter constructor. and...

    C++,please help. I have no idea how to do that begining with zero parameter constructor. and help me to test the method, Write a class template Square Matrix that implements a square matrix of elements of a specified type. The class template should be fully in the Square Matrix.h file. The class uses "raw" pointers to handle the dynamically allocated 2D-array. "Raw" pointers are the classic pointers that you've used before. In addition to it, you will need a variable...

  • // thanks for helping // C++ homework // The homework is to complete below in the...

    // thanks for helping // C++ homework // The homework is to complete below in the stack.h : // 1. the copy constructor // 2. the assignment operator // 3. the destructor // 4. Write a test program (mytest.cpp) to test copy and assignment // 5. Verify destructor by running the test program in Valgrind // This is the main.cpp #include <iostream> #include "stack.h" using namespace std; int main() { Stack<int> intStack; cout << "\nPush integers on stack and dump...

  • I only need the "functions" NOT the header file nor the main implementation file JUST the impleme...

    I only need the "functions" NOT the header file nor the main implementation file JUST the implementations for the functions Please help, if its difficult to do the complete program I would appreciate if you could do as much functions as you can especially for the derived class. I am a beginer so I am only using classes and pointers while implementing everything using simple c++ commands thank you in advanced Design and implement two C++ classes to provide matrix...

  • (The SortedLinkedList class template) Complete the SortedLinkedList class template which is a doubly linked list and...

    (The SortedLinkedList class template) Complete the SortedLinkedList class template which is a doubly linked list and is implemented with a header node and a tail node. // SortedLinkedList.h // SortedLinkedList.h // A collection of data are stored in the list by ascending order #ifndef SORTEDLIST_H #define SORTEDLIST_H using namespace std; template <typename T> class SortedList { private: // The basic single linked list node type. // Nested inside of SortedList. struct NodeType { T data; NodeType* next; NodeType* prev; NodeType(const...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT