问题描述
- vector使用显示越界是什么原因
-
#include
#includeusing namespace std;
void merge( vector& a, int first, int mid, int last )
{
vector s1;
for (auto si = a.begin() + first; si <= a.begin() + mid; ++si)
s1.push_back( *si );
vector s2;
for (auto si = a.begin() + mid + 1; si <= a.begin() + last; ++si)
s2.push_back( *si );
int i = 0; int j = 0; int k = 0;
int len1 = mid - first + 1;
int len2 = last - mid;
for (; ( i < len1 ) && ( j < len2 ); ++k)
{
if (s1[ i ] < s2[ j ])
a[ k ] = s1[ i++ ];
else
a[ k ] = s2[ j++ ];} while (i++ < len1)//调试到这里显示越界,但是此时i = 0,len1 = 1,怎么也想不通为什么会越界 a[ k++ ] = s1[ i ]; while (j++ < len2) a[ k++ ] = s2[ j ];
}
void mergesort( vector& a, int first, int last )
{
if (first < last)
{
int mid = ( first + last ) / 2;
mergesort( a, first, mid );
mergesort( a, mid + 1, last );
merge( a, first, mid, last );
}
}int main()
{
vector a = { 44, 3, 38, 5, 47, 25, 36, 26, 27, 2, 46, 4, 5, 50,99 };mergesort( a, 0, a.size()-1 ); for (auto i : a) cout << i<<" "; cout << endl; return 0;
}
解决方案
i++
->
++i
否则下面i=1了