gpt4 book ai didi

c++ - 将 vector 与 qsort() 一起使用

转载 作者:行者123 更新时间:2023-11-30 02:56:32 24 4
gpt4 key购买 nike

我正在做一项涉及使用 qsort() 的 vector 的家庭作业。我能够获取要编译的代码,但我收到一条错误消息,提示 Expression: vector subscript is out of rangeExpression: Standard C++ Libraries out of range &&0 可以有人帮忙解决我的 vector 下标超出范围的位置和原因吗?

#include    <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <vector>

using namespace std;

#include "functions.h"

typedef vector< int >::size_type size_t;


int main( )
{
ifstream ifs = get_ifs( );

sort( ifs );

return 0;
}


void sort( ifstream &ifs )
{
vector< int > vi;
int value;

while( ifs >> value )
{
vi.push_back( value );
}

cout << "unsorted vi:\n" << vi << '\n';

qsort( vi );

cout << "\nsorted vi:\n" << vi << '\n';
}


void qsort( vector< int > &vi )
{
int bot = 0;
int top = vi.size() - 1;

qsort(vi, bot, top);
}

void qsort( vector< int > &vi, size_t low, size_t high )
{


if (low < high)
{
int split = partition(vi, low, high);
qsort(vi, low, split-1);
qsort(vi, split+1,high);
}
else
{
return ;
}

}

size_t partition( vector<int>& 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] > pivot)
{
vi[top] = vi[bottom];
break;
}
}
while (notdone)
{
top = top-1;

if (top == bottom)
{
notdone = false;
break;
}
if (vi[top] < pivot)
{
vi[bottom] = vi[top];
break;
}
}
}
vi[top] = pivot;
return top;
}





void print_vec( const vector< int > &vi, size_t n, size_t t )
{
cout << vi;

for( size_t i = 0; i < t; ++i )
{
cout << setw( 3 ) << vi[ i ] << ' ';
}

}


ostream &operator <<( ostream &out, const vector< int > &vi )
{
vector< int >::const_iterator iter;

for( iter = vi.begin( ); iter != vi.end( ); ++iter )
{
out << setw( 3 ) << *iter << ' ';
}

return out;
}


ifstream get_ifs( ) // get input file stream
{
string filename; // input file name

cerr << "name of file to read from? ";
cin >> filename;

ifstream ifs( filename, ifstream::in );
if( ! ifs ) // cannot open file infilen
{
cerr << "cannot open input file '" << filename << "'\n";
exit( 1 );
}

return ifs; // return input file stream
}

最佳答案

当您对元素进行分区直到每个分区中只剩下 1 个元素时,如果我理解正确的话,您将返回 0 作为顶部。

当您输入代码时 qsort(vi, low, split-1); split 将包含 0。

您需要处理特殊情况,即您的分区有 1 个元素

关于c++ - 将 vector 与 qsort() 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15398855/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com