问题描述
- 数组类模板Array,类中包括对数组进行排序、查找和求元素和 然后由此产生模板类Array<Box>
- #include
using namespace std;
class Box
{
private:
int a b c;
public:
int V;
Box(int chint kint g)
{
a = ch;
b = k;
c = g;
V = a*b*c;
}
bool operator <(Box &one)
{
int temp = V - one.V;
if (temp < 0)
return true;
else
return false;
}
int operator +(Box &one)
{
return V + one.V;
}
bool operator ==(Box &one)
{
if (V == one.V)
return true;
else
return false;
}
};
template
class Array
{
private:
int size;
T* element;
public:
Array();
~Array(){ delete[]element; }
void sore();
void find();
T add();
int add1()
{
int sum1 = 0;
for (int i = 0; i < size; i++)
{
sum1 = sum1 + element[i];
}
return sum1;
}
};
template
Array::Array()
{
cout << ""输入数组长度:"" << endl;
cin >> size;
element = new T[size];
cout << ""输入数组成员:"" << endl;
for (int i = 0; i < size; i++)
{
cin >> element[i];
}
}
template
void Array::sore()
{
int i j;
T temp;
for (i = 0 ; i < size - 1; i++)
for (j = 0; j < size - 1 - i; j++)
{
if (element[j]>element[j + 1])
{
temp = element[j];
element[j] = element[j + 1];
element[j + 1] = temp;
}
}
for (int i2 = 0; i2 < size; i2++)
{
cout << element[i2] ;
}
}
template
void Array::find()
{
int p = 0;
T num;
cout << ""输入要找的数:"" << endl;
cin >> num;
for (int i = 0; i < size; i++)
{
if (element[i] == num)
{
cout << ""该成员对应的下标为:"" << (i + 1) << endl;
p = 1;
}
}
if (p!=1)
cout << ""不存在!!"" << endl;
}
template
T Array::add()
{
T he=0;
for (int i = 0; i < size; i++)
{
he = he + element[i];
}
return he;
}
int main()
{
ArrayS2;
cout << ""排序:"";
S2.sore();
cout << endl;
S2.find();
cout << ""求和:"";
cout << S2.add1();
cout << endl;*/
return 0;
}
解决方案
时间: 2024-12-21 16:58:02