编写并使用数组类模板Array:(1)类中包括对数组进行排序、查找和求元素和的方法 (2) 然后由此产生模板类Array<int>和Array<Box>(Box重载<、=-、+)
时间: 2024-05-10 12:21:20 浏览: 59
```
#include <iostream>
#include <algorithm> // for std::sort
template <typename T>
class Array {
private:
T* m_data;
int m_size;
public:
Array(int size) : m_size(size) {
m_data = new T[size];
}
~Array() {
delete[] m_data;
}
void sort() {
std::sort(m_data, m_data + m_size);
}
int find(const T& value) {
for (int i = 0; i < m_size; i++) {
if (m_data[i] == value)
return i;
}
return -1;
}
T sum() {
T result = 0;
for (int i = 0; i < m_size; i++) {
result += m_data[i];
}
return result;
}
T& operator[] (int index) {
return m_data[index];
}
};
class Box {
private:
int m_value;
public:
Box(int value = 0) : m_value(value) {}
bool operator< (const Box& other) const {
return m_value < other.m_value;
}
Box& operator= (const Box& other) {
m_value = other.m_value;
return *this;
}
friend std::ostream& operator<< (std::ostream& out, const Box& box) {
out << box.m_value;
return out;
}
};
int main() {
Array<int> intArray(5);
intArray[0] = 3;
intArray[1] = 1;
intArray[2] = 4;
intArray[3] = 2;
intArray[4] = 5;
intArray.sort();
std::cout << "Sorted array: ";
for (int i = 0; i < 5; i++) {
std::cout << intArray[i] << " ";
}
std::cout << std::endl;
int index = intArray.find(4);
std::cout << "Index of value 4: " << index << std::endl;
int sum = intArray.sum();
std::cout << "Sum of array: " << sum << std::endl;
Array<Box> boxArray(3);
boxArray[0] = Box(3);
boxArray[1] = Box(1);
boxArray[2] = Box(2);
boxArray.sort();
std::cout << "Sorted box array: ";
for (int i = 0; i < 3; i++) {
std::cout << boxArray[i] << " ";
}
std::cout << std::endl;
return 0;
}
```
输出:
```
Sorted array: 1 2 3 4 5
Index of value 4: 3
Sum of array: 15
Sorted box array: 1 2 3
```
阅读全文