私はここの私の知恵の終わりにいます、私の友人。2次元配列から値の行にアドレスを返す機能はありますか?
この関数の目的は、2D配列、行番号、および列サイズへのポインタを受け取り、2D配列内の指定された値の行を指すアドレスを戻すことです。私はどのようにこれを達成するために、アドバイスが不明ですか?
ありがとうございます。
double* get_row(double *the_array, int row_num, int col_size) {
cout << "Get Row : "<< the_array[row_num]<< "\n";
return the_array+row_num;}
COUTの理由は、それは私がポインタを返すよ値の右のセットだということを確認することですが、私はそれを正しく実装しました正確にはわかりません。
EDIT:
ここではx
とy
が2Dアレイの座標である場合、完全なコード
#include "TwoDArray.h"
using namespace std;
/*
*
*/
void set_row(double *the_array, int row_num, int col_size, double *row_vals) {
for (int i = 0; i < col_size; i++)
the_array[i] = *row_vals + i;
cout << "Set Row:"<< *the_array << "\n";
}
double get_element(double *the_array, int row_num, int col_size, int col_num) {
double thisElement = (*(the_array + (row_num * col_size)) + col_num);
return thisElement;
}
double* get_row(double *the_array, int row_num, int col_size) {
cout << "Get Row : "<< the_array[row_num]<< "\n";
return the_array+row_num;
}
double sum(double *the_array, int row_size, int col_size) {
double sum = 0.0;
for (int j = 0; j < row_size; j++) {
for (int i = 0; i < col_size * row_size; i++) {
sum += the_array[i] + j;
}
return sum;
}
}
double find_max(double *the_array, int row_size, int col_size) {
double max_so_far = the_array[0];
for (int j = 0; j < row_size; j++)
for (int i = 0; i < col_size * row_size; i++)
if (the_array[i] + j > max_so_far)
max_so_far = the_array[i] + j;
return max_so_far - 1;
}
double find_min(double *the_array, int row_size, int col_size) {
double min_so_far = the_array[0];
for (int j = 0; j < row_size; j++)
for (int i = 0; i < col_size * row_size; i++)
if (the_array[i] + j < min_so_far)
min_so_far = the_array[i] + j;
return min_so_far;
}
int main(int argc, char** argv) {
const int row_size = 2; //i
const int col_size = 3; //j
double B[2][3] = {
{68, 2, 44},
{7, 8, 3}
};
double (*p)[3] = B;
double C[2][3] = {
{1, 1, 1},
{1, 2, 3}};
double (*f)[3] = C;
cout << "\n" << "Sum of all Elements = " << sum(*p, 2, 3) << "\n"; ///Expected: 132
cout << "\n" << "Get Element = " << get_element(*p, 1, 0, 0) << "\n"; //Expected: 68
cout << "\n" << "Largest Element = " << find_max(*p, 2, 3) << "\n"; //Expected: 68
cout << "\n" << "Smallest Element = " << find_min(*p, 2, 3) << "\n"; //Expected: 2
cout << "\n" << "Get Row = " << get_row(*p, 0, col_size) << "\n"; //Expected: 2
set_row(*p, 2, 3, *f);
cout << "\n" << B[2][3];
cout << "\n";
}
を助ける、私は行列の1次元表現に使用してきたいくつかのようなコードを持っています。それは配列の配列ですか、それとも各行を順番に含む単一の配列ですか?あなたの関数の引数は後者を暗示しているようですが、あなたの実装は前者を暗示しているようです。 –
ようこそスタックオーバーフロー。 [The Tour](http://stackoverflow.com/tour)を読み、[ヘルプセンター](http://stackoverflow.com/help/asking)の資料を参考にしてください。ここに聞いてください。 –
_ "しかし、私はそれを正しく実装しているかどうかは確かではありません。" _これはテストケースのためのものです。 –