[英]extracting rows or columns from a 2D-array C++
我想制作一個函數,該函數接收一個二維數組並以簡單數組的形式返回其行之一。 我這樣寫:
int *row(int *array, int lines, int columns, int which)
{
int result[columns];
for (int i=0; i<columns; i++)
{
result[i] = *array[which][i];
}
return result;
}
但是,在第7行中,出現以下錯誤:數組下標的無效類型'int [int]'。 知道如何正確執行此操作嗎? 我也嘗試將2D數組作為數組數組處理,但沒有成功。 我是新手,所以請避免使用過於高級的概念。
謝謝您的幫助!
更新:感謝您的幫助! 現在我的代碼如下:
int n; //rows
int m; //columns
int data[100][100];
int array[100];
int *row(int *array, int rows, int columns, int which)
{
int* result = new int[columns];
for (int i=0; i<columns; i++)
{
result[i] = *array[which*columns+i];
}
return result;
delete[] result;
}
int main()
{
array=row(data, n, m, 0);
}
我仍然在main中遇到錯誤:將'int *'分配給'int [100]'的類型不兼容
現在可能是什么問題? 我也不知道在哪里使用delete []函數釋放數組。
非常感謝你的幫助!
您不能只是這樣做:
int result[columns];
您需要動態分配:
int* result = new int[columns];
另外,您對array
的使用看起來是錯誤的。 如果array
將是單個指針,那么您需要:
result[i] = array[which*columns + i];
“數組”是一維的。 您可以通過以下方式訪問索引為[which] [i]的元素:array [which * columns + i]。 同時刪除星號,因為數組只是單個指針。
編輯:另外,您不能返回本地數組-您需要處理動態內存:
int* result = new int[columns];
然后要特別小心以釋放此內存。 另一種選擇是使用std :: vector。
首先需要修復的錯誤很少。
盡管我知道我不遵循此處的張貼禮節,但我還是建議您從一本好的教科書開始,掌握基礎知識,並在遇到問題時來這里。
數組的大小必須是編譯時常量。
可能不應該使用std::vector
(可能與2D矩陣類一起使用),而不是弄亂數組。
您可以通過使用std::vector
避免所有這些指針算法和內存分配
#include <vector>
#include <iostream>
typedef std::vector<int> Row;
typedef std::vector<Row> Matrix;
std::ostream& operator<<(std::ostream& os, const Row& row) {
os << "{ ";
for(auto& item : row) {
os << item << ", ";
}
return os << "}";
}
Row getrow(Matrix m, int n) {
return m[n];
}
Row getcol(Matrix m, int n) {
Row result;
result.reserve(m.size());
for(auto& item : m) {
result.push_back(item[n]);
}
return result;
}
int main () {
Matrix m = {
{ 1, 3, 5, 7, 9 },
{ 2, 4, 5, 6, 10 },
{ 1, 4, 9, 16, 25 },
};
std::cout << "Row 1: " << getrow(m, 1) << "\n";
std::cout << "Col 3: " << getcol(m, 3) << "\n";
}
double *row(double **arr, int rows, int columns, int which)
{
double* result = new double[columns];
for (int i=0; i<columns; i++)
{
result[i] = arr[which][i];
}
return result;
delete[] result;
}
這將返回該行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.