填充在初始化:
int a[3][3] = { { 1, 4, 7},
{ 2, 5, 8},
{ 3, 6, 9}
};
EDIT(不確定如果解決):
更新到這裏的問題是一個示例應用程序(具有修改以接受來自用戶的輸入)將會給出兩個陣列和後構造的陣列表示是相同的元件和相同的元件的數目的計數:
#include <iostream>
int** make_array(const size_t a_rows, const size_t a_columns)
{
int** result = new int*[a_rows];
for (size_t i = 0; i < a_rows; i++)
{
*(result + i) = new int[a_columns];
}
return result;
}
void print_array(int** a_array, const size_t a_rows, const size_t a_columns)
{
for (size_t r = 0; r < a_rows; r++)
{
for (size_t c = 0; c < a_columns; c++)
{
std::cout << *(*(a_array + r) + c) << " ";
}
std::cout << "\n";
}
std::cout << "\n";
}
int main()
{
// Example data.
int a[3][3] = { { 1, 4, 7},
{ 2, 5, 8},
{ 3, 6, 9}
};
int b[3][3] = { { 1, 2, 3},
{ 4, 5, 6},
{ 7, 8, 9}
};
size_t rows = 3;
size_t columns = 3;
// Create three arrays:
// - two input arrays
// - array that represents which elements are the same
int** in_1 = make_array(rows, columns);
int** in_2 = make_array(rows, columns);
int** diff = make_array(rows, columns);
// Populate with example data.
for (size_t r = 0; r < rows; r++)
{
for (size_t c = 0; c < columns; c++)
{
*(*(in_1 + r) + c) = a[r][c];
*(*(in_2 + r) + c) = b[r][c];
}
}
// Diff.
// The 'diff' array will hold '1' for elements that
// were the same and '0' for elements that were not.
size_t same_count = 0;
for (size_t r = 0; r < rows; r++)
{
for (size_t c = 0; c < columns; c++)
{
*(*(diff + r) + c) = *(*(in_1 + r) + c) == *(*(in_2 + r) + c);
same_count += *(*(diff + r) + c);
}
}
std::cout << "\n";
// Results.
print_array(in_1, rows, columns);
print_array(in_2, rows, columns);
print_array(diff, rows, columns);
std::cout << "Same element count: " << same_count << "\n";
// Free...
return 0;
}
輸出:
$ ./cpp/main.exe
1 4 7
2 5 8
3 6 9
1 2 3
4 5 6
7 8 9
1 0 0
0 1 0
0 0 1
Same element count: 3
我很好奇,你有沒有把任何努力進入發佈前解決這個問題?我知道答案,但爲什麼重複的代碼可以在30秒內通過簡單的Google搜索找到?哦,如果你不喜歡谷歌,這裏是直接鏈接:http://www.cplusplus.com/forum/articles/7459/ – 2012-02-25 15:45:06
我給你的代碼。 'int i = 1; i <= n'不同於'int i = 0;我
2012-02-25 15:59:00
@LuchianGrigore哦,我錯過了。但現在,主要的問題是,如何找到我在說明中解釋的那些數字。 – ddacot 2012-02-25 16:04:35