C ++比较数组中的元素并打印位置

时间:2017-04-24 13:35:23

标签: c++ arrays sorting matrix

我想比较矩阵的每一行的元素,从最小到最大。 但我不想打印我想打印原始位置的排序数组。

0     11.80 79.34 78.23
11.80 0     65.23 45.19 
79.34 65.23 0     90.27
78.23 45.19 90.27 0

在第一行的矩阵中,我想打印1,2,4,3

我的代码到目前为止:

#include <iostream>
#include <fstream>
#include <iomanip>

using namespace std;

int main() {

  string dummy;
  double myArray[4][4];
  int i;
  int j;
  int y;


  ifstream infile("dist.dat");

  cout << "Open file " << "dist.dat" <<" for reading." << endl;

  for (i = 0; i < 4; i++) {
    for (j = 0; j < 4; j++) { 
      infile >> myArray[i][j]; 
      if (!infile) { 
        cout << "***There was a problem trying to read element [" << i << "][" << j << "]" << endl; 
        return 0;
      } 
    } 
  } 
  infile.close();

  cout << "Here's the array from the file" << endl; 
  cout << fixed << setprecision(2); 
  for (i = 0; i < 4; i++) { 
    for (j = 0; j < 4; j++) { 
      cout << setw(10) << myArray[i][j]; 
    }  
    cout << endl;  
  }  
  cout << endl; 
  int x = myArray[i][j];
  for (i = 0; i < 4; i++) {
    for (j = 0; j < 4; j++) {
      if(myArray[i][j] >= x) {
        x = j;
      }
      else {
        x = j + 1;
      }
    }
  cout << x << endl;
  }
  return 0;
}

1 个答案:

答案 0 :(得分:0)

您需要维护另一个具有每行索引的矩阵,然后在原始矩阵的每一行上对其应用相同的操作以对其进行排序。

以下是代码:

#include <iostream>
#include <fstream>
#include <iomanip>

using namespace std;

void swap(int &x, int &y)
{
 int temp = x;
 x = y;
 y = temp;
}

void swap(double &x, double &y)
{
 double temp = x;
 x = y;
 y = temp;
}

int main()
{
  string dummy;
  double myArray[4][4];
  int i;
  int j;
  int y;
  int k;

  ifstream infile("dist.dat");

  cout << "Open file " << "dist.dat" <<" for reading." << endl;

  for (i = 0; i < 4; i++)
  {
    for (j = 0; j < 4; j++)
    {
      infile >> myArray[i][j];
      if (!infile)
      {
        cout << "***There was a problem trying to read element [" << i << "][" << j << "]" << endl;
        return 0;
      }
    }
  }

  infile.close();

  cout << "Here's the array from the file" << endl;
  cout << fixed << setprecision(2);

  for (i = 0; i < 4; i++)
  {
    for (j = 0; j < 4; j++)
    {
      cout << setw(10) << myArray[i][j];
    }
    cout << endl;
  }

  cout << endl;

  int sortedIndices[4][4];

  for (i = 0; i < 4; i++)
  {
    for (j = 0; j < 4; j++)
    {
     sortedIndices[i][j] = j+1;
    }
  }

  int x;

  for (i = 0; i < 4; i++)
  {
    for (j = 0; j < 4; j++)
    {
     x = j;

     for(k = j+1; k < 4; k++)
     {
        if(myArray[i][k] < myArray[i][x])
        {
            x = k;
        }
     }

     swap(sortedIndices[i][j], sortedIndices[i][x]);
     swap(myArray[i][j], myArray[i][x]);
    }
  }

  for (i = 0; i < 4; i++)
  {
    for (j = 0; j < 4; j++)
    {
     cout << setw(10) << sortedIndices[i][j];
    }

    cout<<endl;
  }

  return 0;
}