我有一个2D数组的代码:
#include<iostream>
using namespace std;
const int CITY = 2;
const int DAYS = 3;
int main()
{
int temperature [CITY][DAYS];
int value, rowPosition, columnPosition;
// Insertion
for (int i = 0; i < CITY; i++)
{
for(int j = 0; j < DAYS; j++)
{
cout << "City " << i + 1 << ", Day " << j + 1 << " : ";
cin >> temperature[i][j];
}
}
// Deletion
cout << "Enter row-position to delete: ";
cin >> rowPosition;
cout << "Enter column-position to delete: ";
cin >> columnPosition;
for (int i = rowPosition; i < CITY; i++)
{
for(int j = columnPosition; j < DAYS; j++)
{
temperature[rowPosition][columnPosition] = temperature[rowPosition + 1][columnPosition + 1];
}
}
// Search
cout << "Enter value to search: ";
cin >> value;
for (int i = 0; i < CITY; i++)
{
for(int j = 0; j < DAYS; j++)
{
if(value == temperature[i][j])
{
cout << "The value " << value << " is found at index " << i + 1 << " " << j + 1 << endl;
}
}
}
// Display
for (int i = 0; i < CITY; i++)
{
for(int j = 0; j < DAYS; j++)
{
cout << "City " << i + 1 << ", Day " << j + 1 << " = " << temperature[i][j] << endl;
}
}
return 0;
}
例如,CITY = 2
和DAYS = 3
表示2D数组由2行和3列组成。现在我想从这个2D数组中删除一个元素,比如位置row = 2
,col = 1
的元素。
我尝试了上面提到的删除代码,但它再次显示了相同的数组而没有删除。
答案 0 :(得分:0)
您错过了#include
我看到你要做的是什么,实际上并没有删除任何内容,只是将所有内容都移到了“删除”索引上? 注意:这不是嵌套的for循环。 这就是我要做的事情
temperature[rowPosition][columnPosition] = 0; // in case at the end of array
for (int i = columnPosition; i < DAYS-1; i++)
temperature[rowPosition][i] = temperature[rowPosition][i + 1]; // move all back