CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 7 of 7

Threaded View

  1. #5
    Join Date
    Jun 2006
    Location
    M31
    Posts
    885

    Re: Overloading a matrix constructor for 1 and 2 dimensional arrays.

    Quote Originally Posted by Muthuveerappan View Post
    3) Would be happy if someone can suggest a better solution especially to get rid of the global variables (am not too fond of it)
    With respect to exclusively supporting stack-based arrays, sure (untested):
    Code:
    template< typename T, class Container = std::deque<T> > class Matrix
    {
        public:
        template<std::size_t X> explicit Matrix(const T(& data)[X]) : 
            m_data(data, data + sizeof data / sizeof *data)
        {
        }
    
        template<std::size_t Y, std::size_t X> Matrix(const T(& data)[Y][X]) : 
            m_data(*data, *data + sizeof data / sizeof(T))
        {
        }
    
        friend std::ostream& operator<<(std::ostream& outputStream, const Matrix& matrix)
        {
            std::copy(matrix.m_data.begin(), matrix.m_data.end(), 
                std::ostream_iterator<T> (outputStream, "\t"));
    
            return outputStream;
        }
    
        private:
        Container m_data;
    };
    If not, then a more general solution could be provided; for instance:
    Code:
    template<class InputIterator> Matrix(const InputIterator first, const InputIterator last)
    {
        assert(first <= last); //Some sort of sanity check. =\
    
        //Can call 'reserve' here...
    
        std::copy(first, last, std::back_inserter(m_data));
    }
    Last edited by Plasmator; September 6th, 2009 at 12:03 PM. Reason: Fixed broken assertion, and arithmetic error.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured