### Vector Iterator Not Dereferencable

I'm getting the error as stated in the title at line 80 when I call my binarySearch function. Any ideas why/how to fix?
 ``1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192`` ``````// BinarySearch.cpp // Cedar Wiseman // COSC 2030, Section 11, Spring 2014 // Project04 // March 13, 2014 #include #include #include #include using namespace std; double binarySearch( const vector & v, double target ) { unsigned long low = 0; unsigned long high = v.size(); while( low < high ) { unsigned long 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 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; else if( 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
Last edited on
A. In a vector, v, v.size() is never a valid index (line 17.)
B. binarySearch does not (always) return a value as it promises to do.
Last edited on
Topic archived. No new replies allowed.