我有一個排序字符數組的問題。有一個數組2 * 5 3 4應該從文件中排序,但我可以在代碼中查找錯誤。編譯器只是讀取數組。任何建議,意見數組可以排序
#include <iostream> // cin cout endl
#include <fstream> // ifstream
#include <sstream> // stringstream
#include <stdlib.h> //exit
#include <vector>
#include "insertionSort.h";
using std::cerr;
using std::cout;
using std::endl;
using std::ifstream;
using std::vector;
using namespace std;
const int MAX_CHARS = 200; // max length of each line to read from the input file
template<class T>
void readSortOutput(char* typeName, vector<T> v, ifstream &inStream);
int main()
{
int array_size= 1024;
char *array = new char[array_size];
int possition;
ifstream inStream("/home/xx/Downloads/input.txt");
cout << "Insertion sort algorithm driver program" << endl;
if(inStream.fail())
{
cerr << "Input file opening failed.\n";
exit(1);
}
while (!inStream.eof()&&possition<array_size)
{
inStream.get(array[possition]);
possition++;
}
array[possition-1] = '\0';
cout <<"Display the array" <<endl <<endl;
for (int i=0;array[i] !='\0';i++)
{
cout <<array[i];
}
vector<int> intVector;
readSortOutput((char*)"int", intVector, inStream);
vector<double> dblVector;
readSortOutput((char*)"double", dblVector, inStream);
vector<char> chrVector;
readSortOutput((char*)"char", chrVector, inStream);
inStream.close();
return 0;
}
template<class T>
void readSortOutput(char* typeName, vector<T> v, ifstream &inStream)
{
// read a line from the input stream into a stringstream
char fileLine[MAX_CHARS];
std::stringstream ss;
inStream.getline(fileLine, MAX_CHARS);
ss << fileLine;
// extract elements of the specified type from the stringstream
T elem;
while (ss >> elem) {
v.push_back(elem);
}
cout << endl << typeName << " vector before insertion sort: " << endl;
for (int i = 0; i < v.size(); i++)
cout << v[i] << " ";
cout << endl;
insertionSort(v); // the sort itself
cout << typeName << " vector after insertion sort: " << endl;
for (int i = 0; i < v.size(); i++)
cout << v[i] << " ";
cout << endl;
return;
} // readSortOutput
insertionSort.h
#ifndef INSERTIONSORT_H
#define INSERTIONSORT_H
#include <vector> // vector
#include <iostream> // cin cout endl
#include <fstream> // ifstream
#include <sstream> // stringstream
#include <stdlib.h> //exit
using std::vector;
/*template<class T>
void insertionSort(vector<T>& data); // function replaces the given argument
*/
template<class T>
void insertionSort(vector<T>& data)
{
for (size_t i = 0; i < data.size(); i++)
for (size_t j = i; j < data.size(); j++)
if (data[ j ] < data[ i ])
{ // swap values
T temp = data[ j ];
data[ j ] = data[ i ];
data[ i ] = temp;
}
return;
}
#endif // INSERTIONSORT_H
您遇到什麼_exact_問題? '編譯器只是讀取數組'沒有多大意義,說實話,因爲編譯器的工作是讀取代碼。更重要的是,你可以直接使用'namespace std;'和'cout'和'cerr'等等,而不使用'std ::'。 – ForceBru
剛剛得到這個信息:2 * 5 3 4 –
說實話,我不明白你的評論意思是什麼:'2 * 5 3 4'是什麼意思? – ForceBru