2011-04-25 112 views
1

我想提出關於矩陣運算的另一個問題...矩陣運算,構造問題

template <typename T> 
struct TMatrix 
{ 
    typedef std::vector < std::vector <T> > Type; 
}; 


template <typename T> 
class Matrix 
{ 
    private: 
      typename TMatrix <T>::Type items;  
      const unsigned int rows_count;   
      const unsigned int columns_count; 

    public: 
      template <typename U> 
      //Error, see bellow please 
      Matrix (const Matrix <U> &M): 
        rows_count (M.getRowsCount()), columns_count (M.getColumnsCount()), items (M.getItems()){} 
      unsigned int getRowsCount() const {return rows_count;} 
      unsigned int getColumnsCount() const {return columns_count;} 
      typename TMatrix <T>::Type const & getItems() const {return items;} 
      typename TMatrix <T>::Type & getItems() {return items;} 

編譯代碼,編譯器將停止在這裏:

Matrix (const Matrix <U> &M): 
     rows_count (M.getRowsCount()), columns_count (M.getColumnsCount()), items (M.getItems()){} //Error 

,並顯示以下錯誤:

Error 79 error C2664: 'std::vector<_Ty>::vector(const std::allocator<_Ty> &)' : cannot convert parameter 1 from 'const std::vector<_Ty>' to 'const std::allocator<_Ty> &' 

但我不知道,爲什麼...再次感謝您的幫助...

更新問題:

編譯代碼

template <class T> 
template <typename U> 
Matrix <T> :: Matrix (const Matrix <U> &M) 
: rows_count (M.getRowsCount()), columns_count (M.getColumnsCount()), items (M.getItems().begin(), M.getItems().end()){} 

結果如下:

Error 132 error C2664: 'std::vector<_Ty>::vector(const std::allocator<_Ty> &)' : 
cannot convert parameter 1 from 'const std::vector<_Ty>' to 'const std::allocator<_Ty> &' 
c:\program files\microsoft visual studio 10.0\vc\include\xmemory 208 
+1

它*有*使用矢量向量作爲基礎容器嗎?矩陣中的每一行都在RAM的不同部分,可能會在迭代時多次使緩存失效。在內部使用一維序列容器使一切變得如此簡單。 – Cubbi 2011-04-25 22:39:55

+0

@Cubbi:它還具有以下優點:您可以將一維序列容器地址傳遞給基本矩陣運算(BLAS)的有效例程,或者更復雜的算法,您肯定不想自己編寫代碼(LAPACK)。 – 2011-04-25 22:46:50

+0

@Cubbi,@Alexandre - 原諒我的無知,但矩陣總是矩形?或者它可以有一個鋸齒狀的邊緣? (也就是說,行長在所有行中是不變的?) – 2011-04-25 22:56:36

回答

0

你忘了#include <vector>在頂部和};在文件的結尾。當我將這些添加到代碼中時,它在我的計算機上編譯得很好。

2

您的模板化構造函數Matrix<T>::Matrix<U>(const Matrix<U> &M)旨在構造給定Matrix<U>Matrix<T>。它通過在初始化程序列表中調用構造函數vector<vector<T>>(vector<vector<U>>)來完成此操作。

問題是std::vector沒有提供混合類型的構造函數。

我不知道如何解決這個在初始化列表中。你可以在構造函數的主體中完成它。這裏是你的公共接口允許更新:

Matrix() : rows_count(), columns_count(), items() {} 
template <typename U> 
Matrix (const Matrix <U> M): 
    rows_count (M.getRowsCount()), columns_count (M.getColumnsCount()), items () { 
    for(int i = 0; i < M.getItems().size(); i++) { 
     items.push_back(std::vector<T>(M.getItems()[i].begin(),M.getItems()[i].end())); 
    } 
}