Question

#include <iostream> #include <vector> #include <fstream> #include <time.h> #include <chrono> #include <sstream> #include <algorithm> class Clock...

#include <iostream>
#include <vector>
#include <fstream>
#include <time.h>
#include <chrono>
#include <sstream>
#include <algorithm>

class Clock {
private:
std::chrono::high_resolution_clock::time_point start;
public:
void Reset() {
start = std::chrono::high_resolution_clock::now();
}
double CurrentTime() {
auto end = std::chrono::high_resolution_clock::now();
double elapsed_us = std::chrono::duration std::micro>(end - start).count();
return elapsed_us;
}
};

class books{
private:
std::string type;
int ISBN;
public:
void setIsbn(int x) {
ISBN = x;
}
void setType(std::string y) {
type = y;
}
int putIsbn() {
return ISBN;
}
std::string putType() {
return type;
}
};

std::ostream &operator <<(std::ostream &out, std::vector &myvector) {
for (int i = 0; i < myvector.size(); i++) {
out << myvector[i].putIsbn() << std::endl;
out << myvector[i].putType() << std::endl;
}
return out;
}

int setVectorFile(std::string file, std::vector *myvector) {
std::ifstream myfile;
myfile.open(file);
if (!myfile) {
std::cout << "Error: cannot open file " << file << std::endl;
return -1;
}
std::string character;
while (!myfile.eof()) {
books* pointer;
getline(myfile, character, ',');
pointer = new books;
int x;
std::stringstream convertToInteger(character);
convertToInteger >> x;
pointer -> setIsbn(x);
getline(myfile, character);
pointer ->setType(character);
myvector->push_back(*pointer);
}
return true;
}

int algorithmSort(books x, books y) {
return x.putIsbn() < y.putIsbn();
}

bool binarySearch(std::vector myvector, int search, std::string type) {
int mid;
int low = 0;
int high = myvector.size();
while (low <= high) {
mid = (high + low) / 2;
int midValue = myvector[mid].putIsbn();
std::string midType = myvector[mid].putType();
if (search == midValue && type == midType) {
return midValue;
} else if (search > midValue) {
low = mid + 1;
  
} else {
high = mid - 1;
}
}
return false;
}

bool linearSearch(std::vectormyvector, int search, std:: string type) {
for (int i = 0; i < myvector.size(); i++) {
if (search == myvector[i].putIsbn() && type == myvector[i].putType()) {
return true;
}
}
return false;
}

int main(int argc, char **argv) {
bool found = true;
std::string myfile1, myfile2;
std::vector NewBooks;
std::vector RequestdBooks;
Clock ct;

if (argc != 4 || argv[1] == NULL || argv[2] == NULL || argv[3] == NULL) {
std::cout << "Usage: ./SearchNewBooks ";
std::cout << " " << std::endl;
return -1;
}
myfile1 = argv[1];
myfile2 = argv[2];
char character;
if (setVectorFile(myfile1, &NewBooks) == -1) {
return -1;
}
if (setVectorFile(myfile2, &RequestdBooks) == -1) {
return -1;
}
std::cout << "Choice of search method ([l]inear, [b]inary)?" << std::endl;
std::cin >> character;
std::ofstream out;
out.open(argv[3]);
if (!out) {
return -1;
}
int count = 0;
while (std::cin) {
ct.Reset();
switch (character) {
case 'l':
for (int i = 0; i < RequestdBooks.size(); i++) {
if (linearSearch(NewBooks, RequestdBooks[i].putIsbn(), RequestdBooks[i].putType()) == found) {
count++;
}
}
out << count << std::endl;
std::cout << "CPU time: " << ct.CurrentTime() << " microseconds" << std::endl;
exit(0);
break;
case 'b' :
sort(NewBooks.begin(), NewBooks.end(), algorithmSort);
for (int i = 0; i < RequestdBooks.size(); i++) {
if (binarySearch(NewBooks, RequestdBooks[i].putIsbn(), RequestdBooks[i].putType()) == found) {
count++;
}
}
out << count << std::endl;
std::cout << "CPU time: " << ct.CurrentTime() << " microseconds" << std::endl;
exit(0);
break;
default:
std::cout << "Invalid choice" << std::endl;
std::cout << "Choice of search method ([l]inear, [b]inary)?" << std::endl;
std::cin >> character;
}
}
}

Here is my code for my project everything is correct except binary search and is not correct. I need to used (>) overload operator but I don't know where to use. I want to find book type and isbn has to be matched.

here is my input file:

newbooks.dat

2918,digital
2918,used
2918,new
2821,used

request.dat

2918,digital
2918,used
2918,new

Using linear search I found all 3 book in the found.dat but binary search does not give me all 3 books. It gave me 2 only. Please help me to fix my binary search. I do not know what to do. NEED URGENT! Thanks

0 0
Add a comment Improve this question Transcribed image text
Answer #1

The problem you are facing with binary search code is you always need to initialise as last index of array which high = myvector.size()-1.

But you initialised it as int high = myvector.size();

Below is the code with highlighted part as corrected function

#include <iostream>
#include <vector>
#include <fstream>
#include <time.h>
#include <chrono>
#include <sstream>
#include <algorithm>

class Clock {
private:
std::chrono::high_resolution_clock::time_point start;
public:
void Reset() {
start = std::chrono::high_resolution_clock::now();
}
double CurrentTime() {
auto end = std::chrono::high_resolution_clock::now();
double elapsed_us = std::chrono::duration std::micro>(end - start).count();
return elapsed_us;
}
};

class books{
private:
std::string type;
int ISBN;
public:
void setIsbn(int x) {
ISBN = x;
}
void setType(std::string y) {
type = y;
}
int putIsbn() {
return ISBN;
}
std::string putType() {
return type;
}
};

std::ostream &operator <<(std::ostream &out, std::vector &myvector) {
for (int i = 0; i < myvector.size(); i++) {
out << myvector[i].putIsbn() << std::endl;
out << myvector[i].putType() << std::endl;
}
return out;
}

int setVectorFile(std::string file, std::vector *myvector) {
std::ifstream myfile;
myfile.open(file);
if (!myfile) {
std::cout << "Error: cannot open file " << file << std::endl;
return -1;
}
std::string character;
while (!myfile.eof()) {
books* pointer;
getline(myfile, character, ',');
pointer = new books;
int x;
std::stringstream convertToInteger(character);
convertToInteger >> x;
pointer -> setIsbn(x);
getline(myfile, character);
pointer ->setType(character);
myvector->push_back(*pointer);
}
return true;
}

int algorithmSort(books x, books y) {
return x.putIsbn() < y.putIsbn();
}

bool binarySearch(std::vector myvector, int search, std::string type) {
int mid;
int low = 0;
int high = myvector.size()-1;
while (low <= high) {
mid = (high + low) / 2;
int midValue = myvector[mid].putIsbn();
std::string midType = myvector[mid].putType();
if (search == midValue && type == midType) {
return midValue;
} else if (search > midValue) {
low = mid + 1;
  
} else {
high = mid - 1;
}
}
return false;
}

bool linearSearch(std::vectormyvector, int search, std:: string type) {
for (int i = 0; i < myvector.size(); i++) {
if (search == myvector[i].putIsbn() && type == myvector[i].putType()) {
return true;
}
}
return false;
}

int main(int argc, char **argv) {
bool found = true;
std::string myfile1, myfile2;
std::vector NewBooks;
std::vector RequestdBooks;
Clock ct;

if (argc != 4 || argv[1] == NULL || argv[2] == NULL || argv[3] == NULL) {
std::cout << "Usage: ./SearchNewBooks ";
std::cout << " " << std::endl;
return -1;
}
myfile1 = argv[1];
myfile2 = argv[2];
char character;
if (setVectorFile(myfile1, &NewBooks) == -1) {
return -1;
}
if (setVectorFile(myfile2, &RequestdBooks) == -1) {
return -1;
}
std::cout << "Choice of search method ([l]inear, [b]inary)?" << std::endl;
std::cin >> character;
std::ofstream out;
out.open(argv[3]);
if (!out) {
return -1;
}
int count = 0;
while (std::cin) {
ct.Reset();
switch (character) {
case 'l':
for (int i = 0; i < RequestdBooks.size(); i++) {
if (linearSearch(NewBooks, RequestdBooks[i].putIsbn(), RequestdBooks[i].putType()) == found) {
count++;
}
}
out << count << std::endl;
std::cout << "CPU time: " << ct.CurrentTime() << " microseconds" << std::endl;
exit(0);
break;
case 'b' :
sort(NewBooks.begin(), NewBooks.end(), algorithmSort);
for (int i = 0; i < RequestdBooks.size(); i++) {
if (binarySearch(NewBooks, RequestdBooks[i].putIsbn(), RequestdBooks[i].putType()) == found) {
count++;
}
}
out << count << std::endl;
std::cout << "CPU time: " << ct.CurrentTime() << " microseconds" << std::endl;
exit(0);
break;
default:
std::cout << "Invalid choice" << std::endl;
std::cout << "Choice of search method ([l]inear, [b]inary)?" << std::endl;
std::cin >> character;
}
}
}

Add a comment
Know the answer?
Add Answer to:
#include <iostream> #include <vector> #include <fstream> #include <time.h> #include <chrono> #include <sstream> #include <algorithm> class Clock...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • #include #include #include #include #include #include // NOLINT (build/c++11) #include class Clock { private: std::chrono::high_resolution_clock::time_point start;...

    #include #include #include #include #include #include // NOLINT (build/c++11) #include class Clock { private: std::chrono::high_resolution_clock::time_point start; public: void Reset() { start = std::chrono::high_resolution_clock::now(); } double CurrentTime() { auto end = std::chrono::high_resolution_clock::now(); double elapsed_us = std::chrono::duration std::micro>(end - start).count(); return elapsed_us; } }; class books{ private: std::string type; int ISBN; public: void setIsbn(int x) { ISBN = x; } void setType(std::string y) { type = y; } int putIsbn() { return ISBN; } std::string putType() { return type; } }; std::ostream...

  • fully comments for my program, thank you will thumb up #include <iostream> #include <fstream> #include <string>...

    fully comments for my program, thank you will thumb up #include <iostream> #include <fstream> #include <string> #include <iomanip> using namespace std; struct book { int ISBN; string Author; string Title; string publisher; int Quantity; double price; }; void choice1(book books[], int& size, int MAX_SIZE) { ifstream inFile; inFile.open("inventory.txt"); if (inFile.fail()) cout <<"file could not open"<<endl; string str;    while(inFile && size < MAX_SIZE) { getline(inFile, str); books[size].ISBN = atoi(str.c_str()); getline(inFile, books[size].Title);    getline(inFile, books[size].Author); getline(inFile, books[size].publisher);          getline(inFile,...

  • #include <fstream> #include <iostream> #include <cstdlib> using namespace std; // Place charcnt prototype (declaration) here int...

    #include <fstream> #include <iostream> #include <cstdlib> using namespace std; // Place charcnt prototype (declaration) here int charcnt(string filename, char ch); int main() { string filename; char ch; int chant = 0; cout << "Enter the name of the input file: "; cin >> filename; cout << endl; cout << "Enter a character: "; cin.ignore(); // ignores newline left in stream after previous input statement cin.get(ch); cout << endl; chcnt = charcnt(filename, ch); cout << "# of " «< ch« "'S:...

  • Please add a detailed comment for this program. #include<iostream> #include<string> #include<fstream> #include<sstream> #include<cctype> using namespace std;...

    Please add a detailed comment for this program. #include<iostream> #include<string> #include<fstream> #include<sstream> #include<cctype> using namespace std; int is_palindrome(string word){ int len = word.size(); for(int i=0; i<len/2; i++){ if(toupper(word[i])!=toupper(word[len-i-1])) return 0; } return 1; } int have_vowels3(string word){ int cnt = 0; for(int i=0; i<word.size(); i++){ if(tolower(word[i])=='a' || tolower(word[i])=='e' || tolower(word[i])=='i' || tolower(word[i]) =='o' || tolower(word[i]) == 'u') cnt++; } if(cnt>=3) return 1; else return 0; } int have_consecutives(string word){ for(int i=0; i<word.size()-1; i++){ if(tolower(word[i])=='o' && tolower(word[i+1]=='o')) return 1; } return...

  • #include <iostream> #include <string> #include <fstream> #include <sstream> using namespace std; struct transition{ // transition structure...

    #include <iostream> #include <string> #include <fstream> #include <sstream> using namespace std; struct transition{ // transition structure char start_state, to_state; char symbol_read; }; void read_DFA(struct transition *t, char *f, int &final_states, int &transitions){ int i, j, count = 0; ifstream dfa_file; string line; stringstream ss; dfa_file.open("dfa.txt"); getline(dfa_file, line); // reading final states for(i = 0; i < line.length(); i++){ if(line[i] >= '0' && line[i] <= '9') f[count++] = line[i]; } final_states = count; // total number of final states // reading...

  • *****Complete void example 4, 7, 8, 9, 10 #include <iostream> #include <fstream> #include <vector> #include <string>...

    *****Complete void example 4, 7, 8, 9, 10 #include <iostream> #include <fstream> #include <vector> #include <string> using namespace std; void rtrim(std::string& str, const std::string& chars = "\t\n\v\f\r ") { str.erase(str.find_last_not_of(chars) + 1); } vector<string> *get_words() { vector<string> *words = new vector<string>(); fstream infile; string word; infile.open("words.txt"); getline(infile, word); while(infile) { rtrim(word);     words->push_back(word);     getline(infile, word); } return words; } void example_1(vector<string> *words) { // find words that contain the substring 'pet' and 'cat' // HINT: use find(str, p) method....

  •    moviestruct.cpp #include <iostream> #include <fstream> #include <cstdlib> #include <ostream> #include <fstream> #include <cstdlib> #include <cstring>...

       moviestruct.cpp #include <iostream> #include <fstream> #include <cstdlib> #include <ostream> #include <fstream> #include <cstdlib> #include <cstring> using namespace std; typedef struct{ int id; char title[250]; int year; char rating[6]; int totalCopies; int rentedCopies; }movie; int loadData(ifstream &infile, movie movies[]); void printAll(movie movies[], int count); void printRated(movie movies[], int count); void printTitled(movie movies[], int count); void addMovie(movie movies[],int &count); void returnMovie(movie movies[],int count); void rentMovie(movie movies[],int count); void saveToFile(movie movies[], int count, char *filename); void printMovie(movie &m); int find(movie movies[], int...

  • #include <iostream> #include <iomanip> #include <cstdlib> #include <fstream> #include <string> #include <vector> #include <sstream> using namespace...

    #include <iostream> #include <iomanip> #include <cstdlib> #include <fstream> #include <string> #include <vector> #include <sstream> using namespace std; void DisplayMenu() {    cout << "1. E games\n";    cout << "2. T games\n";    cout << "3. M games\n";    cout << "4. Total Games\n";    cout << "5. Exit\n"; } double total(double egames, double tgames, double mgames) {    int totalgames = egames + tgames + mgames;    cout << "There are " << totalgames << " games\n";    return...

  • vector.h: #ifndef VECTOR_H #define VECTOR_H #include <algorithm> #include <iostream> #include <cassert> template <typename T> class Vector...

    vector.h: #ifndef VECTOR_H #define VECTOR_H #include <algorithm> #include <iostream> #include <cassert> template <typename T> class Vector {     public:         Vector( int initsize = 0 )         : theSize( initsize ),          theCapacity( initsize + SPARE_CAPACITY )         { objects = new T[ theCapacity ]; }         Vector( const Vector & rhs )         : theSize( rhs.theSize),          theCapacity( rhs.theCapacity ), objects( 0 )         {             objects = new T[ theCapacity ];             for( int k = 0; k < theSize; ++k)                 objects[ k ] = rhs.objects[ k...

  • graph binary search for size and time c++ //System Libraries #include <iostream> #include <string> #include <cstdlib> #include <ctime> #include <iomanip> #include <alg...

    graph binary search for size and time c++ //System Libraries #include <iostream> #include <string> #include <cstdlib> #include <ctime> #include <iomanip> #include <algorithm> using namespace std; //User Libraries //Global Constants, no Global Variables are allowed //Math/Physics/Conversions/Higher Dimensions - i.e. PI, e, etc... //Function Prototypes //Execution Begins Here! int main(int argc, char** argv) { int n, i, arr[50], search, first, last, middle,count=0,count_in,tot; clock_t start, end; float duration; cout<<"Enter total number of elements :"; cin>>n; cout<<"Enter numbers"; for (i=0; i<n;i++) cin>>arr[i]; cout<<"Enter a...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT