Как читать строки из текстового файла в вектор для поиска?

0
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;
}
}
  • 2
    Это: while (!infile.eof()) было бы неправильно. Вы можете начать там. Исправьте это, и вы будете удивительно близки.
  • 0
    попробуйте while (std :: getline (infile, wordLine))
Показать ещё 2 комментария
Теги:
vector
binary-search
iostream

1 ответ

3

Возможно, вы не захотите делать все это, для вас существует стандартная библиотека cpp:

std::sort(list.begin(),list.end());
binary_search (list.begin(), list.end(), str);

Эти две строки достаточно, чтобы выполнить двоичный поиск по вектору.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню