我在我的用户定义的向量中收到垃圾。垃圾在擦除功能之后出现这是代码
#if 1 // Make it 1 to enable this code
#include <iostream>
using namespace std;
class Vector{
protected:
int l;
int* v;
public:
Vector():l(0),v(0){
cout << "\nBase class: Vector: Default constructor" << endl;
}
Vector( int len ):l(len),v(new int[l]) {
cout << "Vector: Overloaded constructor" << endl;
}
void set( int i, int val)
{
if( l )
v[i] = val;
else{
cout << "Error: zero size vector\n exiting..." <<endl;
exit(5);
}
}
int get( int i)
{
if( l )
return v[i];
else{
cout << "Error: zero size vector\n exiting..." <<endl;
exit(5);
}
}
~Vector(){
cout << "Base dextructor" <<endl;
delete [] v;
}
};
class Vector1:public Vector{
private:
public:
Vector1():Vector(){
cout << "Derived class: Vector1:: Default constructor" << endl;
}
//my functions
int size()
{
return l;
}
int front()
{
return Vector::get(0);
}
int end()
{
return Vector::get(l-1);
}
void swap(int a,int b)
{
int temp=v[a];
v[a]=v[b];
v[b]=temp;
}
void find(int val)
{
bool flag=false;
for(int i=0;i<l;i++)
{
if(v[i]==val)
{
flag=true;
}
}
if(flag==true)
cout<<"\nValue ="<<val<<" =Exists in Vector";
else
cout<<"\nValue ="<<val<<" =doesnot Exists in Vector";
}
void erase(int val)
{
int *temp=new int[l-1];
int k=0;
for(int i=0;i<l;i++)
{
if(v[i]!=val)
{
temp[i]=v[i];
k++;
}
}
delete []v;
l=l-1;
v=new int[l];
for(int i=0;i<l;i++)
{
v[i]=temp[i];
}
}
int resize( int len )
{
if( l )
delete [] v;
l = len;
v = new int[l];
return (v!=0);
}
void set( int i, int val)
{
if( i>= 0 && i<l )
Vector::set( i, val );
else{
cout << "Error: index out of range\n exiting..." <<endl;
exit(3);
}
}
int get( int i)
{
if( i>= 0 && i<l )
return Vector::get(i);
else{
cout << "Error: index out of range\n exiting..." <<endl;
exit(3);
}
}
int & operator [](int i)
{
return v[i];
}
Vector1( int len ):Vector(len)
{
}
};
int main()
{
Vector vec;
Vector1 v1;
v1.resize( 4 );
v1.set( 2, 4);
v1.set( 1, 5);
v1.set( 0, 6);
int x = v1[2];
v1[3] = 77;
cout<<"\nSize of vector is=\n"<<v1.size();
//v1.set( 5, 4); // erroneous value
cout<<"\nFront of vector is=\n"<<v1.front();
cout<<"\nEnd of vector is=\n"<<v1.end();
//do swap between values
cout<<"\n";
v1.swap(1,3);
//now values are
cout<<"v1[1] is equals to= "<<v1[1];
cout<<"v1[3] is equals to= "<<v1[3];
v1.find(5);
v1.find(100);
cout<<"\nNow v1[0] is equals to= \n"<<v1[0];
v1.erase(6);
cout<<"\nNow v1[0] is equals to= \n"<<v1[0]<<" "<<v1[1];
cout<<"\n";
}
#endif
输出是这个
v1[0] 应该是 5