我正在实现一个动态数组。我的默认数组容量为10。当我尝试添加10个以上的随机字符串时,出现错误“访问冲突写入位置。this-> ** _ Myproxy **为0xFDFDFDFD”。而我被扔到xutility文件的第239行。
但是,当我将数组设置为包含整数或字符时,它就可以正常工作。当我添加少于10个字符串时也是如此,所以我不知道问题出在哪里。也许我以一种扭曲的方式释放记忆?
这是我的主要功能,也是Arr类的构造函数,析构函数和void添加函数。
#include "pch.h"
#include <iostream>
#include <string>
#include <time.h>
using namespace std;
template < typename T >
class Arr
{
T * data;
int capacity,len;
public:
Arr()
{
capacity = 10;
len = 0;
data = new T[ capacity ];
}
~Arr()
{
delete[] data;
}
void add( T value )
{
if( capacity <= len ) //powiekszenie jesli nie ma miejsca
{
capacity = 2 * capacity;
T * temp = new T[ capacity ];
for( int i = 0; i <= len; i++ )
{
//temp[i] = data[i];
temp[ i ] = move( data[ i ] );
}
delete[] data;
data = temp;
}
data[ len++ ] = value;
}
const T retVal( const int index )
{
if( index >= len )
{
cout << "Nie ma elementu o takim indeksie,zwracam wartosc el.
[0]: ";
return this->data[ 0 ];
}
else
return this->data[ index ];
}
void change( int index,T new_data )
{
if( index > len )
{
cout << "Nie ma takiego elementu" << endl;
return;
}
data[ index ] = new_data;
}
void clean()
{
if( len == 0 )
{
cout << "Tablica pusta!" << endl;
return;
}
len = len - 1;
for( int i = len; i >= 1; --i )
{
data[ i ].~T();
len--;
}
}
void getData()
{
cout << endl << "Akt. pojemnosc tablicy: " << capacity << endl;
cout << "Liczba el. w tablicy: " << len << endl;
}
void delLast()
{
data[ len-- ].~T();
}
void printArr()
{
for( int i = 0; i < len; i++ )
{
cout << data[ i ] << " ";
}
//cout << "Koniec" << endl;
}
};
string randomString( int length )
{
string rs;
static const char chars[] =
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
int size = sizeof( chars );
for( int i = 0; i < length; i++ )
{
rs = rs + chars[ rand() %( size - 1 ) ];
}
return rs;
}
int main()
{
Arr < string > * tab = new Arr < string >();
const int order = 7;
const int n = pow( 10,order );
clock_t start = clock();
double max_time_per_element = 0.0;
srand( time( 0 ) );
for( int i = 0; i < n; i++ )
{
string el = randomString( 3 );
clock_t start2 = clock();
tab->add( el );
clock_t stop2 = clock();
double time_per_element =( stop2 - start2 ) / CLOCKS_PER_SEC; // obliczenie czasu pojedynczej operacji dodawania
if( time_per_element > max_time_per_element )
{
time_per_element = max_time_per_element;
cout << max_time_per_element << endl;
}
}
clock_t stop = clock();
double general_time =( stop - start ) / CLOCKS_PER_SEC;
tab->getData();
cout << "Czas calej operacji to: " << general_time << endl;
tab->printArr();
tab->clean(); // czyszczenie tablicy wraz z uwalnianiem pamieci danych
delete tab;
return 0;
}
[EDIT]正如某些人所建议的那样,我粘贴了整个代码,而不是像开始时那样粘贴了某些部分。请原谅我,我是新来的!