Note that there are some explanatory texts on larger screens.

plurals
  1. POusing vectors with qsort()
    text
    copied!<p>I am working on a homework assignment involving vectors using qsort(). I am able to get the code to compile, but I am receiving an error saying <code>Expression: vector subscript is out of range</code> and <code>Expression: Standard C++ Libraries out of range &amp;&amp;0</code> Can anyone help as to where and why my vector subscript is out of range?</p> <pre><code>#include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;iomanip&gt; #include &lt;string&gt; #include &lt;vector&gt; using namespace std; #include "functions.h" typedef vector&lt; int &gt;::size_type size_t; int main( ) { ifstream ifs = get_ifs( ); sort( ifs ); return 0; } void sort( ifstream &amp;ifs ) { vector&lt; int &gt; vi; int value; while( ifs &gt;&gt; value ) { vi.push_back( value ); } cout &lt;&lt; "unsorted vi:\n" &lt;&lt; vi &lt;&lt; '\n'; qsort( vi ); cout &lt;&lt; "\nsorted vi:\n" &lt;&lt; vi &lt;&lt; '\n'; } void qsort( vector&lt; int &gt; &amp;vi ) { int bot = 0; int top = vi.size() - 1; qsort(vi, bot, top); } void qsort( vector&lt; int &gt; &amp;vi, size_t low, size_t high ) { if (low &lt; high) { int split = partition(vi, low, high); qsort(vi, low, split-1); qsort(vi, split+1,high); } else { return ; } } size_t partition( vector&lt;int&gt;&amp; vi, size_t low, size_t high ) { int pivot = vi[high]; int bottom = low - 1; int top = high; bool notdone = true; while(notdone) { while(notdone) { bottom += 1; if (bottom == top) { notdone = false; break; } if (vi[bottom] &gt; pivot) { vi[top] = vi[bottom]; break; } } while (notdone) { top = top-1; if (top == bottom) { notdone = false; break; } if (vi[top] &lt; pivot) { vi[bottom] = vi[top]; break; } } } vi[top] = pivot; return top; } void print_vec( const vector&lt; int &gt; &amp;vi, size_t n, size_t t ) { cout &lt;&lt; vi; for( size_t i = 0; i &lt; t; ++i ) { cout &lt;&lt; setw( 3 ) &lt;&lt; vi[ i ] &lt;&lt; ' '; } } ostream &amp;operator &lt;&lt;( ostream &amp;out, const vector&lt; int &gt; &amp;vi ) { vector&lt; int &gt;::const_iterator iter; for( iter = vi.begin( ); iter != vi.end( ); ++iter ) { out &lt;&lt; setw( 3 ) &lt;&lt; *iter &lt;&lt; ' '; } return out; } ifstream get_ifs( ) // get input file stream { string filename; // input file name cerr &lt;&lt; "name of file to read from? "; cin &gt;&gt; filename; ifstream ifs( filename, ifstream::in ); if( ! ifs ) // cannot open file infilen { cerr &lt;&lt; "cannot open input file '" &lt;&lt; filename &lt;&lt; "'\n"; exit( 1 ); } return ifs; // return input file stream } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload