如何将字符串从文本文件读取到要搜索的向量中
How to read strings from a text file into a vector, to be searched?
I can read a file line my line and I know the fundamentals of Binary Search. how can i make my strings get into a vector or an array where i can call my Binsearch function and return true or false?
I have most of it.
这些文件现在正在测试中,但基本上我一行一行地阅读文件,逐行打印以证明......将字符串放入矢量中调用我的 BS 函数以使用我拥有的其他文本文件搜索字符串......
我的文件的内容并不重要,除了字符串都在 1 列中。
#include <cstdlib>
#include <vector>
#include <string>
#include <fstream>
#include <iostream>
using namespace std;
int binarySearch(vector<string> list, string str)
{
int first, mid, last;
bool found;
first = 0;
last = list.size()-1;
found = false;
while(!found&&first<=last)
{
mid=(first+last)/2;
if(list[mid]==str)
found = true;
else if(list[mid]>str)
last=mid-1;
else
first=mid+1;
}
if(found)
return mid;
else
return -1;
}
//
int main() {
vector<string> list;
string str;
ifstream infile;
infile.open("testdata.txt");
if (!infile)
cout<<"Input file cannot be openned!"<<endl;
cout<<"---------------------------------"<<endl;
cout<<"List of words inserted into Trie:"<<endl;
cout<<"---------------------------------"<<endl;
cout<<endl;
string wordLine;
while (!infile.eof()){
infile >> wordLine;
list.push_back(wordLine); //this is my attempt to put strings into vector
cout<<wordLine<<endl;
}
ifstream searchFile;
searchFile.open("searchdata.txt");
if(!searchFile)
cout<<"Search file cannot be openned!"<<endl;
string searchLine;
int loc =binarySearch(list, str);
while (!searchFile.eof()){
searchFile >> searchLine;
if (loc == -1)
cout << searchLine <<" => FOUND!" << endl;
else
cout << searchLine <<" => NOT FOUND." <<endl;
cout << searchLine << endl;
return 0;
}
}
您可能不想做所有这些,cpp 标准库为您服务:
std::sort(list.begin(),list.end());
binary_search (list.begin(), list.end(), str);
这两行足以对向量进行二叉搜索。
相关文章:
- 向量上的线性搜索
- 对的排序向量 (std::vector<pair<int, int>>) 按对的第一个元素搜索并更新第二个元素值
- 哪个更快:在 1d 向量中按字符串搜索还是在 2d 向量中按向量搜索?
- C++:使用类在向量中搜索特定元素时,我得到了错误的结果
- 搜索并替换结构向量中的值
- 我可以做些什么来改进指针向量中的此搜索?
- 迭代向量以获得搜索功能
- 有没有办法搜索向量的元素,<String>然后检查它是否包含特定的字符,如果它确实打印了它
- 用户输入字符串的结构的搜索向量
- 搜索向量时出错
- 如何在 c++ 中搜索向量并获取元素的位置
- boost::元组的搜索向量
- 搜索向量
- 在 c++ 中搜索向量的一部分
- 使用二叉搜索搜索向量的上限
- 使用地图库构建电话目录搜索向量
- 基于元素的自定义键搜索向量
- 线性搜索向量[i]的响应时间为0ms,而向量.at(i)的响应时间为0ms
- 使用正则表达式搜索向量
- 如何在c++中有效地搜索向量