C ++(线性搜索和排序)

时间:2018-09-26 09:33:31

标签: c++ computer-science

有关C ++的帮助。我正在努力的两件事

  1. 我正尝试对列表名称进行线性搜索,但由于某种原因出现消息“ ABSENT!”。输入错误名称时不会出现。我该如何解决?

  2. 我正在尝试按姓氏的升序对输入的名称进行字母排序,但是我真的不知道如何将其用于循环和数组。

下面是到目前为止我要进行编码的内容(上面说线性搜索和排序是我需要帮助的地方,需要进行修改)。

#include <iostream>
#include <string>
#include <iomanip>
using namespace std;

const int Students = 10;
int numStudents = 0;
string StudentName[Students];
int found = -1;
string SearchName;

int main() {
        cout << "Enter the number of students (1-10): ";
        cin >> numStudents;

    for (int i = 0; i < numStudents; i++) {
        cout << "Enter a name: ";
        cin.ignore();
        getline(cin, StudentName[i]);
    }

    cout << "\nEnter a search name: ";
    cin.ignore();
    getline(cin, SearchName);

    **//Linear Search
    for (int i = 0; i < numStudents; i++) {

        if (StudentName[i] == SearchName)
            found = i;
            cout << "PRESENT! Found in position " << found << endl;

        if (StudentName[i] != SearchName)
                found = 0;
                cout << "ABSENT!" << endl;
    }
    //Sorting
    for (int i = 0; i < numStudents - 1; i++) {
        for (int j = i + 1; j < numStudents; j++)
            if (StudentName[i] > StudentName[j]) {
                string t = StudentName[i];
                StudentName[i] = StudentName[j];
                StudentName[j] = t;
            }
    }
    cout << "\nThe Sorted list is:" << "\n";**


    system("pause");
    return 0;
}

1 个答案:

答案 0 :(得分:4)

此代码

    if (StudentName[i] == SearchName)
        found = i;
        cout << "PRESENT! Found in position " << found << endl;

    if (StudentName[i] != SearchName)
            found = 0;
            cout << "ABSENT!" << endl;

缺少if语句的括号。应该是

    if (StudentName[i] == SearchName) {
        found = i;
        cout << "PRESENT! Found in position " << found << endl;
    }

    if (StudentName[i] != SearchName) {
            found = 0;
            cout << "ABSENT!" << endl;
    }

但是代码仍然不正确,因为您必须先检查所有名称,才能知道自己没有找到名称。因此从逻辑上讲,“未找到”的测试只能在for循环之后进行。

我会写类似这样的代码

//Linear Search
found = -1;
for (int i = 0; i < numStudents; i++) {

    if (StudentName[i] == SearchName) {
        found = i;
        break; // we've found it, quit the loop
    }

}

if (found == -1) // did we find it?
    cout << "ABSENT!" << endl;
else
    cout << "PRESENT! Found in position " << found << endl;