【问题标题】:Counting Search Comparisons C++计数搜索比较 C++
【发布时间】:2018-01-22 21:29:51
【问题描述】:

此程序在字典文本文件中搜索用户输入的单词并输出它所在的行。我需要计算在线性搜索和二进制搜索中查找单词的比较次数。现在它说进行了零比较。任何关于在何处或如何实施这些计数器的想法将不胜感激。

string linearSearch(const vector<string> &L, string k);
string binarySearch(const vector<string> &L, string k, int a = 0, int b = -1);
int count1 = 0;
int count2 = 0;

int main()
{

    ifstream inFile;
    inFile.open("dictionary.txt");

    vector < string > words;
    string line;

    while (getline(inFile, line))
    {
        words.push_back(line);
    }

    inFile.close();
    string userWord;
    cout << "Search for a word: " << endl;
    cin >> userWord;

    if (words.empty())
    {
        return -1;
    }

    cout << "Using binary search, the word " << userWord << " is in slot "
            << binarySearch(words, userWord) << ". There were " << count2
            << " comparisons  made." << endl;

    cout << "Using linear search, the word " << userWord << " is in slot "
            << linearSearch(words, userWord) << ". There were " << count1
            << " comparisons made." << endl;

    return 0;
}
string linearSearch(const vector<string> &L, string k)
{

    for (int i = 0; i < L.size(); ++i)
    {
        count1++;
        if (L[i] == k)
        {
            count1++;
            return to_string(i);
        }
    }
    return to_string(-1);

}
string binarySearch(const vector<string> &L, string k, int a, int b)
{

    ++count2;
    if (b == -1)
    {
        b = L.size();
    }
    int n = b - a;

    if (n == 0)
    {
        return to_string(-1); //?
    }

    int mid = (a + b) / 2;

    if (L[mid] == k)
    {
        ++count2;
        return to_string(mid);
    }
    else if (L[mid] > k)
    {
        ++count2;
        return binarySearch(L, k, a, mid);
    }
    else
    {
        count2 += 2;
        return binarySearch(L, k, mid + 1, b);
    }
    return to_string(-1);

}

【问题讨论】:

    标签: c++ file search vector


    【解决方案1】:

    哦哦,这看起来像是由序列点引起的未定义行为(有关详细信息,请参阅this question)。

    引用该问题的答案,

    单个运算符的操作数和单个表达式的子表达式的求值顺序以及副作用发生的顺序是未指定的。

    您正试图在同一个序列点对同一个变量(计数之一)执行 set 和 get。哪个会先发生(set 或 get)是未定义的。

    把你的cout一分为二,一切都应该解决了。

    cout << "Using binary search, the word "<< userWord << " is in slot " << 
        binarySearch(words,userWord) << ".";
    cout << "There were " << count2 << " comparisons made." << endl;
    
    cout << "Using linear search, the word "<< userWord << " is in slot " << 
        linearSearch(words,userWord) << ".";
    cout << "There were " << count1 << " comparisons made." << endl;
    

    【讨论】:

      猜你喜欢
      • 2018-09-23
      • 1970-01-01
      • 2018-11-08
      • 1970-01-01
      • 1970-01-01
      • 2020-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多