// BinarySearch.cpp
// Cedar Wiseman
// COSC 2030, Section 11, Spring 2014
// Project04
// March 13, 2014
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
usingnamespace std;
double binarySearch( const vector<double> & v, double target )
{
unsignedlong low = 0;
unsignedlong high = v.size();
while( low < high )
{
unsignedlong mid = (low + high) / 2;
if( target > *v.end() ) //used to check if lower bound is greater that last number in vector
return -1;
if( target < *v.begin() ) //used to check if upper bound is lower than first number in vector
return -2;
if( target >= v.at(mid) && target > v.at(mid-1) ) //make sure it's first instance of target
{
if( target <= v.at(mid+1) )
return mid;
else
low += low;
}
if( target == v.at(mid) && target == v.at(mid-1) ) //find first instance of target
high -= high;
if( target < v.at(mid) ) //this is what makes it a binary search
high = mid;
else
low = mid + 1;
}
}
int main()
{
string filename, filename2;
vector<double> vec;
cout << "Enter filename of sorted doubles: " << endl;
cin >> filename;
ifstream infile ( filename );
if (infile) // check if file is open
{
double value;
// read the elements in the file into a vector
while ( infile >> value )
vec.push_back( value );
}
else
cout << filename << " failed to open" << endl;
cout << "Enter filename of double pairs: " << endl;
cin >> filename2;
ifstream infile2 ( filename2 );
if ( infile2 )
{
double a, b;
while ( infile2 >> a >> b )
{
cout << "The range being searched is " << a << " to " << b << endl;
if( binarySearch( vec, a ) == -1 )
cout << "The specified file has no values in this range." << endl;
elseif( binarySearch( vec, b ) == -2 )
cout << "The specified file has no values in this range." << endl;
else
cout << "There are " << binarySearch( vec, b ) - binarySearch( vec, a ) << " values in this range." << endl;
}
}
else
cout << filename2 << " failed to open" << endl;
return 0;
}
Okay, I realized it's because I was using *v.begin() and *v.end() instead of v.at(low) and v.at(high), but now when running the program, I get a "std::out_of_range at memory location 0x003EF580" error