Problem 8: 删除数组元素
Description
定义Array类,其中只有一个int类型的数组,数组元素个数未知。
重载其<<、>>、-运算符。其中"<<“输出所有的数组元素,两两之间用1个空格隔开;”>>“根据输入的格式读取数组元素;”-"接收一个int类型的参数a,将数组中与a相等的元素删除。
Input
输入有3行。第一行N>0;第二行是N个整数,是数组元素;第3行是一个int类型数,是需要从数组中删除的数。
Output
见样例。
Sample Input
10
1 2 3 4 5 1 2 3 4 5
1
Sample Output
1 2 3 4 5 1 2 3 4 5
2 3 4 5 2 3 4 5
一
#include <iostream>
#include <vector>
using namespace std;
class Array
{
private:
vector<int> v;
public:
friend istream & operator >> (istream & is,Array & c)
{
int a;
is >> a;
int n;
for(int i=0;i<a;i++){
cin >> n;
c.v.push_back(n);
}
return is;
}
friend ostream & operator << (ostream & os,const Array & c)
{
int t=c.v.size();
int flag=0;
for(int i=0;i<t;i++){
if(c.v[i]==-1)
continue;
if(!flag){
flag++;
os << c.v[i];
}
else{
os << " " << c.v[i];
}
}
os << endl;
return os;
}
Array & operator - (int a)
{
vector<int>::iterator it;
for(it=v.begin();it!=v.end();it++){
if(*it==a)
*it=-1;
}
return *this;
}
};
int main()
{
int a;
Array arr;
cin>>arr;
cout<<arr;
cin>>a;
arr = arr - a;
cout<<arr;
return 0;
}
二
#include <iostream>
#include <cstring>
using namespace std;
class Array
{
private:
int *a;
int sum;
public:
friend istream & operator >> (istream & is,Array & c)
{
int n;
is >> n;
c.sum=n;
c.a=new int[n+1];
for(int i=0;i<n;i++)
cin >> c.a[i];
return is;
}
friend ostream & operator << (ostream & os,const Array & c)
{
int flag=0;
int n=c.sum;
for(int i=0;i<n;i++){
if(c.a[i]==-1)
continue;
if(!flag){
flag=1;
os << c.a[i];
}
else
os << " " << c.a[i];
}
os << endl;
return os;
}
Array & operator - (int b)
{
int n=sum;
for(int i=0;i<n;i++){
if(a[i]==b)
a[i]=-1;
}
return *this;
}
};
int main()
{
int a;
Array arr;
cin>>arr;
cout<<arr;
cin>>a;
arr = arr - a;
cout<<arr;
return 0;
}
三
#include <iostream>
#include <list>
using namespace std;
class Array
{
public :
list<int> num;
friend istream &operator>>(istream &is, Array &p)
{
int n; is>>n;
for(int i=0; i<n; i++)
{
int temp; is>>temp;
p.num.push_back(temp);
}
return is;
}
friend ostream &operator<<(ostream &os, Array &p)
{
list<int>::iterator pp;
for(pp=p.num.begin(); pp!=p.num.end(); pp++)
{
if(pp==p.num.begin())
os<<*pp;
else
os<<" "<<*pp;
}
os<<endl;
return os;
}
Array &operator-(int a)
{
num.remove(a);
return *this;
}
};
int main()
{
int a;
Array arr;
cin>>arr;
cout<<arr;
cin>>a;
arr = arr - a;
cout<<arr;
return 0;
}