Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何让气泡排序和选择排序的计时器工作,它总是显示为零_C++_Sorting_Timer_Bubble Sort_Selection Sort - Fatal编程技术网

C++ 如何让气泡排序和选择排序的计时器工作,它总是显示为零

C++ 如何让气泡排序和选择排序的计时器工作,它总是显示为零,c++,sorting,timer,bubble-sort,selection-sort,C++,Sorting,Timer,Bubble Sort,Selection Sort,我的程序运行得非常好,除了我希望它显示执行冒泡排序和选择所花费的时间外,我的程序中确实有代码,但它始终显示0。请帮忙 #include <iostream> #include <iomanip> #include <vector> #include <stdlib.h> using namespace std; struct student { //structure student unsigned int StuNo; string La

我的程序运行得非常好,除了我希望它显示执行冒泡排序和选择所花费的时间外,我的程序中确实有代码,但它始终显示0。请帮忙

#include <iostream> 
#include <iomanip>
#include <vector>
#include <stdlib.h>

using namespace std;

struct student { //structure student
unsigned int StuNo;
string LastName;
string FirstName;
double Gpa;
unsigned int Age;
string Major;
string College;

};

void clearCIN(void);
int inputInt(string, int, int);
double inputDouble(string, double, double);
string inputString(string, int, int);
// Note: changed "int" to "unsigned int", changed int to size_t
bool findstunum( unsigned int, vector<student>);
void initArrays (int[], double []);
char displayMenu(void);
void addstudent(vector<student> &);
void display(vector<student>);
void bubblesort(vector<student> &);
void selectionsort(vector<student> &);
void addrandomstudents(vector<student> &);
long double startTime;
long double endTime;



int main(int argc, const char * argv[]) {

vector<student> myStudents; //Vector Student

srandom((unsigned int)time(NULL));
char userChoice;
bool keepdisplaying =true;

student tempstudent;

cout << "Welcome to our student management system\n========================================\n";
while (keepdisplaying) {      //displaying menu
    userChoice = displayMenu();
    switch (toupper(userChoice)) {

        case 'A':             //If user inputs 'A'
            addstudent(myStudents);
            break;
            //else

        case 'B':             //If user inputs 'B'
            bubblesort(myStudents);
            break;

        case 'S':             //If user inputs 'S'
            selectionsort(myStudents);
            break;

        case 'L':             //If user inputs 'l'
            display (myStudents);
            break;

        case 'X': keepdisplaying = false;  //if user wants to break.
            break;

        case 'R':
            addrandomstudents(myStudents);
            break;
    }
}

cout << endl << "Thank You for using our student management program\n";
cout << endl << "Have a great day!\n";
//
//End the program with an exit message
//
return 0;
} //main


//
//Clear the CIN input buffer to avoid problems
//
void clearCIN(void) {
cin.clear();
cin.ignore(32768, '\n');
return;
}   //clearCIN


//Input a integer value to be returned to the calling function.  Also, validate the
//the minimum and maximum value of the integer input.
//
int inputInt(string promptString, int minValue, int maxValue) {
int userInput;

cout << promptString << " \n";
while (true) {
    cin >> userInput;
    if (!cin.fail()) {
        char myChar = cin.peek();
        if (myChar == '\n')
            if (userInput >= minValue && userInput <= maxValue)
                break;
            else {
                cout << "Invalid value entered.  Should be between " << minValue << " and " <<        maxValue << " Please try again\n";
                clearCIN();
            }//else
            else {
                cout << "Invalid value entered.  Should be between " << minValue << " and " << maxValue << " Please try again\n";
                clearCIN();
            }//else
    }//if
    else {
        cout << "Invalid integer value entered. Please try again.\n";
        clearCIN();
    }//else
}
clearCIN();
return userInput;
}//inputInt

//
//Input a double value to be returned to the calling function.  Also, validate the
//the minimum and maximum value of the double input.
//
double inputDouble(string promptString, double minValue, double maxValue) {
double userInput;

cout << promptString << " \n";
while (true) {
    cin >> userInput;
    if (!cin.fail()) {
        char myChar = cin.peek();
        if (myChar == '\n')
            if (userInput >= minValue && userInput <= maxValue)
                break;
            else {
                cout << "Invalid value entered.  Should be between " << minValue << " and " <<         maxValue << " Please try again\n";
                clearCIN();
            }//else
            else {
                cout << "Invalid value entered.  Should be between " << minValue << " and " << maxValue << " Please try again\n";
                clearCIN();
            }//else
    }//if
    else {
        cout << "Invalid double value entered. Please try again.\n";
        clearCIN();
    }//else
}
clearCIN();
return userInput;
}//inputdouble

//
//Input a string to be returned to the calling function.
//
string inputString(string promptString, int minLength, int maxLength) {
string userInput;

while (true) {
    cout << promptString << "\n";
    getline(cin, userInput);
    if (userInput.size() < minLength || userInput.size() > maxLength) {
        cout << "The string you entered is too short or too long.  Should be " << minLength << "      to " << maxLength << " in Length\n";
        cout << "Please try again\n";
    }//if
    else
        break;
}//while
return userInput;
}//inputString


bool findstunum(unsigned int toFind, vector<student> numArray) {

for (size_t y=0; y<numArray.size(); y++) {
    if (numArray[y].StuNo == toFind)
        return true;
    else {}
}//for

return false;
}//findstudentnum
//
//Input a char for the menu
//
char displayMenu(void) {
char userSelection = ' ';   //The menu selection given by the user
bool keepAsking = true;     //While this is true, the while loop will continue to operate.

while (keepAsking) {
    cout << "Main Menu\n";
    cout << "---------\n";
    cout << "<A>dd a student\n";
    cout << "<L>ist students\n";
    cout << "<R>andomly generate 1000\n";
    cout << "<B>ubble sort by ID\n";
    cout << "<S>election sort by ID\n";
    cout << "e<X>it program\n";
    cin >> userSelection;

    switch (toupper(userSelection)) {
        case 'L':
        case 'l':
        case 'A':
        case 'a':
        case 'X':
        case 'x':
        case 'S':
        case 's':
        case 'B':
        case 'b':
        case 'R':
        case 'r':
            keepAsking = false; //Since the user has entered one of these, then we don't
            break;              //need to keep asking.
        default:
            cout << "Invalid Selection, please try again\n\n"; //Not sure this would ever     happen...
    }//switch
}//while
clearCIN(); //Always clear the CIN when a cin >> is done, just in case a getline will be       executed.
return userSelection;
}//displaymenu

void addrandomstudents(vector<student> &students) {
for(int i = 0; i < 1000; i++) {
    student tempstudent;
    tempstudent.Gpa   = (double)(random() % 100) / 25.0;

    bool duplicateFound = false;
    do {
        tempstudent.StuNo = random() % 1000;
        duplicateFound = false;

        for(int j = 0; j < students.size(); j++) {
            if(students[j].StuNo == tempstudent.StuNo) {
                duplicateFound = true;
                break;
            }
        }
    } while(duplicateFound);
    tempstudent.FirstName = "joe"; //inputString("Enter the student's First name:", 1, 20);
    tempstudent.LastName = "Smith";// inputString("Enter the student's Last name:", 1, 20);
    tempstudent.Age   = 18;        // inputInt("Please Enter students age", 1, 100);
    tempstudent.Major = "Computer Science"; // inputString("Please Enter students major", 1,     1000);
    tempstudent.College = "UCSD";  // inputString("Please Enter students College", 1, 40);


    students.push_back(tempstudent);
    }

cout << "Thousand Students generated"  << endl;
}

void addstudent ( vector<student> &students){
cout << "New Student"  << endl;
student tempstudent;
bool keepGoing = true;
while (keepGoing) {


    tempstudent.StuNo = inputInt("Please enter student ID:", 1, 1000);

    // keepGoing = false; //out of while
    if (findstunum(tempstudent.StuNo, students))
        cout << "Student number already exists, please try again" << endl;
    else {

        keepGoing = false;
    }//else
}//while

tempstudent.Gpa   = inputDouble("Please enter the student's gpa", 0, 4);
tempstudent.FirstName = inputString("Enter the student's First name:", 1, 20);
tempstudent.LastName = inputString("Enter the student's Last name:", 1, 20);
tempstudent.Age   = inputInt("Please Enter students age", 4, 80);
tempstudent.Major = inputString("Please Enter students major", 1, 1000);
tempstudent.College = inputString("Please Enter students College", 1, 40);


students.push_back(tempstudent);

}

void display ( vector<student> students){
cout << endl << endl;
cout << "student Listing" << endl << endl;
cout << setw(10) << "Student ID" << setw(20) << "Student Name" << setw(16) << "Student GPA" <<   setw(15) << "Student Age" << setw(18) << "Student Major" << setw(25) << "Student College" << endl;
cout << setw(10) << "==========" << setw(20) << "============" << setw(16) << "===========" <<   setw(15) << "===========" << setw(18) << "=============" <<setw (25) << "===============" << endl;
for (int y=0; y< students.size(); y++) {
    cout << fixed << setprecision(2) << setw(10) << students[y].StuNo << setw(20) <<   students[y].LastName + " " + students[y].FirstName << setw(16) << students[y].Gpa << setw(15)   <<students[y].Age << setw(18) << students[y].Major << setw(25) << students[y].College << endl;
}
}

//
//
//BUBBLE SORT
//
//

void bubblesort (vector<student> &students){
student tempStudent;
bool changed = true;

clock_t startingTime = clock();  //Timer begins

if (students.size() == 0){
    cout <<"Error, No students to sort!\n";
    return;              }

while (changed) {
    changed = false;
    for (int i=0; i<students.size()-1; i++) {
        if (students[i].StuNo >
            students[i+1].StuNo) {
            tempStudent = students[i];
            students[i] = students[i+1];
            students[i+1] = tempStudent;
            changed = true;
        }       //if
        else { }
    }//for
}

cout <<"Done Sorting!\n";

clock_t endTime = clock();  //Timer Ends
cout << "It took ";
cout << (endTime - startingTime)/CLOCKS_PER_SEC;
cout << " seconds"<< endl;
}


//
//
//SELECTION SORT
//
//


void selectionsort(vector<student> &students)

{   student tempstudent;
int startScan, minIndex, minValue;

startScan = 0;
clock_t startingTime = clock();         //Timer for selection Sort begins

for(startScan = 0; startScan < students.size() - 1; startScan++)

{
    minIndex = startScan;
    minValue = students[startScan].StuNo;
    for(int index = startScan + 1; index < students.size(); index++)
    {
        if (students[index].StuNo < minValue)
        {
            minValue = students[index].StuNo;
            minIndex = index;
        }
    }

    tempstudent = students[minIndex];
    students[minIndex] = students[startScan];
    students[startScan] = tempstudent;


}
cout <<"Done Sorting!\n";

clock_t endTime = clock();
cout << "It took ";
cout << (endTime - startingTime) / CLOCKS_PER_SEC ;   //Timer Ends
cout << " seconds"<< endl;
}
#包括
#包括
#包括
#包括
使用名称空间std;
结构学生{//结构学生
无符号整数StuNo;
字符串LastName;
字符串名;
双Gpa;
无符号整数;
弦乐大调;
弦学院;
};
void-clearCIN(void);
int输入(字符串,int,int);
双输入双输出(字符串、双输出、双输出);
字符串输入字符串(字符串,int,int);
//注:将“int”更改为“unsigned int”,将int更改为size\u t
布尔findstunum(无符号整数,向量);
void initarray(int[],double[]);
字符显示菜单(无效);
void addstudent(向量&);
虚空显示(矢量);
void-bubblesort(向量&);
无效选择排序(向量和);
学生(向量&)无效;
长双星时间;
双端时间长;
int main(int argc,const char*argv[]{
vector myStudents;//vector Student
srandom((无符号整数)时间(NULL));
字符用户选择;
bool keepdisplay=true;
学生临时工;

cout如果您使用的是C++11-则使用:

#包括
#包括
int main()
{
使用名称空间std::chrono;
time_t start=system_clock::to_time_t(system_clock::now());
用于(自动i=0;i<100000000;+i)
;
时间差=系统时钟::到时间(系统时钟::现在())-开始;

std::cout试着这样写:

cout << (endTime - startingTime) / (double)CLOCKS_PER_SEC ;

请不要给出更少的代码。切掉无用的(理解问题)函数。然而,对10000个元素进行排序并不那么耗时。它还会在几秒钟内完成吗?