Переменные результаты не соответствуют cout

Так что я довольно новичок в C ++, и у меня есть это назначение класса. Обычно я обращаюсь к моему профессору за помощью, но он не отвечает на электронные письма для студентов, и у нас один раз в неделю. Я пытался заставить это работать в течение нескольких дней со странными результатами, так что здесь проблема.

Вот подсказка:

Сортировать массив из одного столбца и / или отсортировать двумерный массив
символов в любом столбце. Вот что я использовал как мой
спецификация шаблона.

Вот класс, который он использовал для использования (мы не можем изменить это):

//This class sorts arrays either ascending or descending
template<class T>
class Prob2Sort
{
private:
int *index;  //Index that is utilized in     the sort
public:
Prob2Sort(){index=NULL;}; //Constructor
~Prob2Sort(){delete []index;};  //Destructor
T * sortArray(const T*,int,bool); //Sorts a single column array
T * sortArray(const T*,int,int,int,bool); //Sorts a 2 dimensional array
};

и вот программа драйвера (также не может коснуться этого):

cout<<"The start of Problem 2, the sorting problem"<<endl;
Prob2Sort<char> rc;
bool ascending=true;
ifstream infile;
infile.open("Problem2.txt",ios::in);
char *ch2=new char[10*16];
char *ch2p=ch2;
while(infile.get(*ch2)){cout<<*ch2;ch2++;}
infile.close();
cout<<endl;
cout<<"Sorting on which column"<<endl;
int column;
cin>>column;
char *zc=rc.sortArray(ch2p,10,16,column,ascending);
for(int i=0;i<10;i++)
{
for(int j=0;j<16;j++)
{
cout<<zc[i*16+j];
}
}
delete []zc;
cout<<endl;

И вывод:

Выход из этой проблемы.

Начало проблемы 2, проблема сортировки
Lcekoeddhoffbmg
Lkcmggjcdhhglif
Cgldjhcekjigcdd
Cgldjhcekjigcdn
Bffmdbkcenlafjk
Fggdijijegfblln
Jjlncnimjldfedj
Amliglfohajcdmm
Balgfcaelhfkgeb
Kmlhmhcddfoeilc

Сортировка по столбцу 15
Cgldjhcekjigcdn
Fggdijijegfblln
Amliglfohajcdmm
Bffmdbkcenlafjk
Jjlncnimjldfedj
Lcekoeddhoffbmg
Lkcmggjcdhhglif
Cgldjhcekjigcdd
Kmlhmhcddfoeilc
Balgfcaelhfkgeb

Теперь я кое-что изменил, чтобы заставить его работать; вот мой сумасшедший код в main.cpp:

cout<<"The start of Problem 2, the sorting problem"<<endl;
Prob2Sort<char> rc;
bool ascending=true;
ifstream infile;
infile.open("Problem2.txt",ios::in);
char *ch2=new char[(4*17)+ 1];
char *ch2p=ch2;
while(infile.get(*ch2)){ch2++;}

infile.close();
cout<<endl;
cout<<"Sorting on which column"<<endl;
int column;
cin>>column;
char *zc=rc.sortArray(ch2p,4,17,column,ascending);
for(int i=0;i<4;i++)
{
for(int j=0;j<17;j++)
{
cout<<zc[i*17+j];
}
}
delete []zc;
cout<<endl;

Теперь вот мой класс:

template<class T>
T* Prob2Sort<T>::sortArray(const T* arry, int rows, int cols, int column, bool order)
{
// put into new array to sort and return
T* a_ray = new T[(rows*cols) + 1];

for(int i=0;i<rows;i++)
{
for(int j=0;j<cols;j++)
{
a_ray[i*cols+j] = arry[i*cols+j];
}
cout << endl;
}

for(int i=0;i<rows;i++)
{
for(int j=0;j<cols;j++)
{
cout << a_ray[i*cols+j] ; // displays fine
}
cout << endl;
}

T temp;
bool test = true;

do
{
test = false;
for(int i = 0; i < rows - 1; i++)
{
cout << "Row " << i << endl;
if(a_ray[i*cols+column] > a_ray[(i+1)*cols+column])
{
cout << "ELEMENT 1 IS " << a_ray[i*cols+column] << endl;
temp = arry[i*cols+column];
cout << "TEMP IS " << temp << endl;
a_ray[i*cols+column] = a_ray[(i+1)*cols+column];
cout << "ELEMENT 1 NEW is  " << a_ray[(i)*cols+column] << endl;
cout << "ELEMENT 2 is " << a_ray[(i+1)*cols+column] << endl;
a_ray[(i+1)*cols+column] = temp;
cout << "ELEMENT 2 NEW is  " << a_ray[(i+1)*cols+column] << endl;
test = true;
}

}
}while(test);

Теперь проблема в том (и у меня было это прежде, чем я коснулся всего) была … не знаю, как это объяснить, но я добавил эти койки, чтобы посмотреть на проблему, поэтому я опубликую вывод
Я выбираю строку 0 для сортировки, так, как у меня есть, он сортирует только один символ в каждом элементе, поэтому я пока не пытался делать то, что хочет мой профессор.

 // this is the file read in (i also has 2 elements at end of each line for the newline
//characters which I can see in a hex editor)

abcdefghijklmno
ABCDEFGHIJKLMNO
1234567890pqrst
uvwxyzPQRSTUVWX
Row 0
ELEMENT 1 IS a
TEMP IS a
ELEMENT 1 NEW is  A
ELEMENT 2 is A
ELEMENT 2 NEW is  a
Row 1

// **PORBLEM HERE***ELEMENT 1 IS a
TEMP IS A

//**the two couts above should be the same... as you can see why here,

cout << "ELEMENT 1 IS " << a_ray[i*cols+column] << endl;
temp = arry[i*cols+column];
cout << "TEMP IS " << temp << endl;

//////////////////////////////// should be same value!!!! but it is not
// t only does this every other loop if I remember right. it will not change the vlauebut retain the last one in it

ELEMENT 1 NEW is  1
ELEMENT 2 is 1

ELEMENT 2 NEW is  A

Спасибо за любого, кто помогает, извините за мой беспорядок, но я действительно нуждаюсь в этом, и я не могу понять, что происходит, и даже мой профессор в какой-то момент, когда я смог его спросить, не смог, но мы все еще должны обратиться я просто не могу исправить эту ошибку

1

Решение

Задача ещё не решена.

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector