我把它做成3x4的矩阵形式
我也不确定如何使用指针,因为我想改变和替换的数字是arr[3][4]
,而不是通常的arr[5]
using namespace std;
#include <iomanip>
int main(){
int i;
int j;
int *change;
int number; // not sure how to use the pointer to reference a [3][4] array //
int arr[3][4] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
for (int i = 0; i < 3; i++) // not sure if there is a way where i dont have to write every number and just have it go from 1 to 12 //
{
for (int j = 0; j < 4; j++)
{
cout << setw(8)<<arr[i][j] << ' '; // to make it look organized and aligned//
}
cout <<endl;
}
cout << "number" << ' ';
cin >> number; // i woud insert the number here//
cout << arr[3][4];
return 0;
}
,应该看起来像这样(假设我选择了6)
1 2 3 4
5 7 8 9
10 11 12 0
您想要执行的操作对于单维范围是自然的,而对于多维范围则不是。有一些标准的算法可以在单一维度范围内实现您的目标。
对于范围视图,获得元素的单维视图相当简单:
// flat view of the array
auto flat_arr = arr | std::ranges::views::join;
// move elements to overwrite the removed elements
auto remaining = std::ranges::remove(flat_arr, number);
// fill the ramaining space with zeroes
std::ranges::fill(remaining, 0);
不使用范围,可以通过定义自定义迭代器实现相同的目的。或者,您可以使用单维数组,并通过一些数学运算转换二维索引。例子:
constexpr std::size_t rows = 3, cols = 4;
int arr[rows*cols] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
// move elements to overwrite the removed elements
auto last_it = std::remove(std::begin(arr), std::end(arr), number);
// fill the ramaining space with zeroes
std::fill(last_it, std::end(arr), 0);
for (std::size_t i = 0; i < rows; i++)
{
for (std::size_t j = 0; j < cols; j++)
{
std::cout
<< std::setw(8)
// transform 2D to 1D
<< arr[i * cols + j]
<< ' '
;
}
std::cout << 'n';
}