0

I want a 2-dim array to print out on the same line as string word. I cant seem to figure out how to get a 2-dim array to do this, does anyone know how to do this?

void Sort(string word[],float grades[][8], int number)
{
	int i,j=o, temp;
	string aName;
	float aName2[][];

	for (i=0; i<(names - 1); i++)
	{
		temp = i;
		aName = worde[i];
		aName2=grades[i][j];
			
		for(int k=i+1; k<names; k++)
		{
			if (word[k] < aName)
			{
				aName = word[k];
				aName2[i][j]=grades[k][8];
				temp = k;
			}
		}
				word[temp] = word[i];
				grades[temp][j]=grades[i][j];
				word[i] = aName;
				grades[i][j]=aName2[][];
				
	}

}
2
Contributors
1
Reply
2
Views
9 Years
Discussion Span
Last Post by Radical Edward
1

The ideal way to do this is to encapsulate the data into an object that defines a comparison operator. Then you can sort the objects instead of trying to sort parallel arrays:

#include <algorithm>
#include <iostream>
#include <stdexcept>
#include <string>

namespace EdRules {
  using namespace std;

  class Student {
    string _name;
    double _grades[8];
  public:
    Student(const string& name);
    const string& name() const;
    double& operator[](int i);
    const double& operator[](int i) const;
    bool operator<(const Student& student);
    friend ostream& operator<<(ostream& os, const Student& student);
  };

  Student::Student(const string& name)
    : _name(name)
  {
    for (int i = 0; i < 8; ++i)
      _grades[i] = 0;
  }

  const string& Student::name() const { return _name; }

  double& Student::operator[](int i)
  {
    if (i < 0 || i >= 8)
      throw out_of_range("Index must be between 0 and 8");

    return _grades[i];
  }

  const double& Student::operator[](int i) const
  {
    if (i < 0 || i >= 8)
      throw out_of_range("Index must be between 0 and 8");

    return _grades[i];
  }

  bool Student::operator<(const Student& student)
  {
    return _name < student._name;
  }

  ostream& operator<<(ostream& os, const Student& student)
  {
    os << student._name;

    for (int i = 0; i < 8; ++i)
      os << (i == 0 ? '{' : ',') << student._grades[i];

    return os << '}';
  }
}

void ShowStudents(EdRules::Student a[], int size)
{
  for (int i = 0; i < size; ++i)
    std::cout << a[i] << '\n';
  std::cout << '\n';
}

int main()
{
  using EdRules::Student;

  Student a[5] = {
    Student("test c"),
    Student("test b"),
    Student("test d"),
    Student("test a"),
    Student("test e")
  };

  for (int i = 0, k = 0; i < 5; ++i) {
    for (int j = 0; j < 8; ++j)
      a[i][j] = ++k;
  }

  ShowStudents(a, 5);
  std::sort(a, a + 5);
  ShowStudents(a, 5);
}

This way you don't have to worry about how to index the arrays, how to copy them, and all of the other limitations that come up with the native array type. :)

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.