如何从二维数组中删除

How to delete from 2D array?

本文关键字:删除 二维数组      更新时间:2023-10-16

我有一个外部文件

1 4 12 3
13 3 22 5
14 22 2 34
222 11 3 31

,我想删除x列和y行。我怎样才能把它打印到外部文件中呢?

它是一个4行4列4元素的二维矢量。

#include<iostream>
#include<fstream>
using namespace std;
void main ()
{
    int a[100][100],m,n;
    ifstream f("mat.txt");
    ofstream b("out.txt");
    f>>n;
    for(int i=0; i<n; i++)
    {
        for(int j=0; j<n; j++)
        {
            f>>a[i][j];
        }
    }
    for(int i=0; i<n; i++)
    {
        for(int j=0; j<n; j++)
        {
            b<<a[i][j]<<" ";
        }
        b<<endl;
    }
}

在本例中,我已经硬编码了x、y和文件名的值。

#include <iostream>
#include <fstream>
using namespace std;
int main() {
  ifstream fin("in.txt");
  ofstream fout("out.txt");
  int i, j, x = 1, y = 2;
  if (fin.is_open() && fout.is_open()) {
    for (i = 0; i < 16; ++i) {
      fin >> j;
      if (i % 4 != x && i / 4 != y) {
        fout << j;
        if (i % 4 == 3) {
          fout << endl;
        } else {
          fout << " ";
        }
      }
    }
    fin.close();
    fout.close();
  }
  return 0;
}

可能您需要使用一些容器而不是普通的2d数组,以防从中间推入和弹出。尝试使用此https://i.stack.imgur.com/G70oT.png通过关键字std,container,choose.

来获取正确或搜索图像。