2017-07-20 8 views
0

2D行列の転置を探していて、2D配列と行列の値の数を入力および返す関数 を作成したい2D行列の転置。以下のよう 私はC++2D配列を関数パラメータとして与え、2D配列を関数の戻り値の型として返す

#include <iostream> 
#include <string> 

using namespace std; 
//int** transpose(int arr[][] , int n); 
int k=2; 
int ** transpose(int wt[1][k] , int n) 
{ 
    int trans[n][1]; 
    for(int i=0;i<n;i++) 
    { 
     trans[i][1] = wt[1][i]; 
    } 
    return trans ; 
} 
int main() 
{ int n; 
cin >> n; 
int wt_vect[1][n]; 
    for(int i=0;i<n;i++) 
    { 
    wt_vect[1][i] = 0.7; 
    } 
int trans[n][1] = transpose(wt_vect , n); 

    } 

しかし、取得エラーログに次のコードを書かれている

7時30分:エラー:バインドされた配列は 7時32分のトークンの前に整数定数「]」ではありません。エラー:予期しない ')'前 '、'トークン ' 7:34:' int 'の前に予期しない非修飾IDがある

機能を使用して転置を見つけるのを手伝ってください。アドバンス

+0

このヘルプをいているのですか? https://stackoverflow.com/questions/16449359/getting-error-array-bound-is-not-an-integer-constant-before-token –

+0

int wt_vect [1] [n] '(ここで、 'n'は変数です)は(標準の)C++ではありません。 – max66

+0

そして、 'wt_vect [1]'が** second ** elemenにアクセスするのを観察してください。 'wt_vect'の最初の次元が' 1'ならば 'wt_vect [0] [i]'と書いてください – max66

答えて

2

することはできませんCスタイルの配列を避ける。

ディメンションの実行時間がわかっている場合は、std::arrayを使用できます。

std::vectorを使用することができます(2次元目は実行時間を知っています)。

以下は、完全な例

#include <vector> 
#include <iostream> 
#include <stdexcept> 

template <typename T> 
using matrix = std::vector<std::vector<T>>; 

template <typename T> 
matrix<T> transpose (matrix<T> const & m0) 
{ 
    // detect the dim1 of m0 
    auto dim1 = m0.size(); 

    // detect the dim2 of m0 (throw id dim1 is zero) 
    auto dim2 = m0.at(0U).size(); 

    for (auto const & r : m0) 
     if (dim2 != r.size()) 
     throw std::runtime_error("no consistent matrix"); 

    // new matrix with switched dimension 
    matrix<T> ret(dim2, std::vector<T>(dim1)); 

    // transposition 
    for (auto i = 0U ; i < dim1 ; ++i) 
     for (auto j = 0U ; j < dim2 ; ++j) 
     ret[j][i] = m0[i][j]; 

    return ret; 
} 


int main() 
{ 
    std::size_t n; 

    std::cin >> n; 

    matrix<int> mat(1U, std::vector<int>(n)); 

    for (auto i = 0U ; i < n ; ++i) 
     mat[0U][i] = 7; 

    auto tam = transpose(mat); 
} 
0

で おかげで基本的に配列サイズがコンパイル時に知られるように持っているが、基本的にそれはあなたがC++を使用している場合は、私が提案する任意の値を持つことができる変数、値なしまたは変更値

+0

次に問題を解決するにはどうしたらいいですか? – user3455556

関連する問題