【问题标题】:C++ (Linear Search and Sorting)C++(线性搜索和排序)
【发布时间】:2019-03-02 00:59:18
【问题描述】:

帮助 C++。我正在努力解决的两件事

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

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

以下是我迄今为止的编码(其中说线性搜索和排序是我需要帮助并且需要修改的地方)。

#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;
}

【问题讨论】:

  • std::find/std::sort 可能会有所帮助。

标签: c++ computer-science


【解决方案1】:

这段代码

    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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-05
    • 2018-07-09
    • 1970-01-01
    • 2012-08-28
    • 2015-08-13
    • 2019-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多