c++ - 简单的二进制搜索对我不起作用。我正在尝试从文本文件中搜索一个单词
问题描述
我用 C++ 构建了一个程序,它从 txt 文件中获取单词并输入到程序中。然后程序将这些单词存储到数组中。现在,我想使用二进制搜索在数组中搜索特定单词。
我的txt文件有以下文字:
hello
world
hi
how
are
you
i
am
fine
thank
welcome
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
using namespace std;
int binarySearch(string words[], const string& x,int n)
{
int l = 0 ;
int r = n - 1;
while (l <= r)
{
int m = l + (r - l) / 2;
int res;
if (x == (words[m]))
res = 0;
// Check if x is present at mid
if (res == 0)
return m;
// If x greater, ignore left half
if (x > (words[m]))
l = m + 1;
// If x is smaller, ignore right half
else
r = m - 1;
}
return -1;
}
int main () {
ifstream inFile;
inFile.open("test.txt");
if(inFile.fail()){
cerr << "Error opening file"<< endl ;
exit(1);
}
string x1;
string words[100];
int count=0,i=0;
string str;
while( !inFile.eof()) {
inFile >> x1;
words[i]=x1;
count++;
i++;
}
for (i=0;i<100;i++){
cout<< words[i]<<endl;
}
string x;
x = "how";
int n = 14;
int result = binarySearch(words , x,n);
if (result == -1)
cout << ("\nElement not present");
else
cout << ("Element found at index ") << result;
return 0;
}
除了第一个词 Hello 之外,我找不到其他词。所以请帮助我。
解决方案
希望这项工作
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
using namespace std;
int binarySearch(string words[], const string& x, int n)
{
int l = 0;
int r = n - 1;
while (l <= r)
{
int m = l + (r - l) / 2;
int res = 0;
if (x == (words[m]))
res = 0;
// Check if x is present at mid
if (res == 0)
return m;
// If x greater, ignore left half
if (x > (words[m]))
l = m + 1;
// If x is smaller, ignore right half
else
r = m - 1;
}
return -1;
}
int main() {
ifstream inFile;
inFile.open("test.txt");
if (inFile.fail()) {
cerr << "Error opening file" << endl;
exit(1);
}
string x1;
string words[100];
int count = 0, i = 0;
string str;
while (!inFile.eof()) {
inFile >> x1;
words[i] = x1;
count++;
i++;
}
for (i = 0; i < 100; i++) {
cout << words[i] << endl;
}
string x;
x = "fine";
int n = 11;
int result = binarySearch(words, x, n);
if (result == -1)
cout << ("\nElement not present");
else
cout << ("Element found at index ") << result;
return 0;
}
推荐阅读
- c# - 如何将下拉列表选定的数据传递到另一个表并在 asp.Net MVC 中更新该表
- apache - 谁能阻止对 htpp 服务器的攻击(我有 access_log)
- java - 如何在 Activity 中使用结果对象?
- angular - Angular v11 库项目中 Stryker 的正确配置?
- android - Webview setDownloadListener 文件不下载同名
- bash - 理解set - - "$@" "-h" 的含义
- python - 为什么 pd.read_csv 不接受 Windows 文件路径中的变量名?
- c++ - 文件系统 value_type 指向字符串的指针?
- javascript - 错误:passport.initialize() 中间件未使用(代码顺序正确)
- javascript - 如何访问类组件中的上下文以进行本机反应?