首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

排序无法在文件中生成结果,该如何解决

2012-03-02 
排序无法在文件中生成结果---------------------------.htemplate typename T class dataList{private:i

排序无法在文件中生成结果
---------------------------
.h
template <typename T> class dataList{
private:
   
  int arraySize;
  void swap(const int m1, const int m2);//swap函数声明
  int minKey(const int low, const int high);//minKey函数声明
public:
  T *element;
  dataList(int size = 10): arraySize(size),element(new T[size]){}
  ~dataList(){delete [] element;}
  void sort();//sort函数
};

//swap函数定义
template <typename T> void dataList<T> :: swap(const int m1, const int m2){
  T temp = element[m1];
  element[m1]=element[m2];
  element[m2]= temp;
}
//minkey函数定义
template <class T> int dataList<T>::minKey(const int low, const int high){
  int min = low;
  for (int k=low+1;k<=high;k++)
  if(element[k] < element[min]) min = k;
  return min;
}
//sort函数定义
template <class T> void dataList<T>::sort(){
  for(int i =0; i<arraySize-1; i++){
  int j = minKey(i, arraySize-1);
  if (j!= i ) swap(j,i);
  }
}
-----------------------------------------------------------
.cpp
#include <iostream>
#include <fstream>
#include "Sorting.h"

using namespace std;

void main()
{
   
ifstream inData;
ofstream outData;
  inData.open("DataIn.txt");
outData.open("DataOut.txt");

cout<<"Please input several numbers to the file .The program will write them in an acsend sequence.";
cout<<"Please input the quantity of the numbers."<<endl;
int quantity;
cin>>quantity;
dataList<int> list1(quantity);
  int i=0;
while(!inData)
{
inData>>list1.element[i];
i++;
}
cout<<"The numbers you input are:"<<endl;
for(int j=0;j<i;j++)
{
cout<<list1.element[j]+" ";
}

list1.sort();

int m=0;
  while(!outData)
{
outData<<list1.element[m]+" ";  
m++;
}
cout<<"The sorted list is:"<<endl;
for(int n=0;n<i;n++)
{
cout<<list1.element[n]+" ";
}
}
在DataIn.txt里装入20个整数,quantity输入为20,无法产生结果。
在visual studio里编译output里显示:
'实验070609.exe': Loaded 'D:\Documents and Settings\Administrator\My Documents\Visual Studio 2005\Projects\数据结构实习\Sorting-实验070906\Debug\实验070609.exe', Symbols loaded.
'实验070609.exe': Loaded 'C:\WINDOWS\system32\ntdll.dll', No symbols loaded.
'实验070609.exe': Loaded 'C:\WINDOWS\system32\kernel32.dll', No symbols loaded.
The program '[2328] 实验070609.exe: Native' has exited with code 0 (0x0).

这个模板是老师给的,做了点小手脚。本来T *element是private,但是我没办法在cpp文件里读取element数组。请高手指点。

[解决办法]
while(!inData) 

inData > >list1.element[i] ; 
i++; 

这里是不是要控制数据边界???


这的环境都重装了,现在也没法试试你的问题。看看楼下会有什么说法。

热点排行