您好,登錄后才能下訂單哦!
#include <iostream>
template <typename T>
class Array {
private:
T *data;
int size;
public:
Array(int size) : size(size) {
data = new T[size];
}
~Array() {
delete[] data;
}
T& operator[](int index) {
if (index < 0 || index >= size) {
throw std::out_of_range("Index out of bounds");
}
return data[index];
}
void fill(T value) {
for (int i = 0; i < size; i++) {
data[i] = value;
}
}
void print() {
for (int i = 0; i < size; i++) {
std::cout << data[i] << " ";
}
std::cout << std::endl;
}
// Optimized function to find the maximum value in the array
T findMax() {
T max = data[0];
for (int i = 1; i < size; i++) {
if (data[i] > max) {
max = data[i];
}
}
return max;
}
};
int main() {
Array<int> arr(5);
arr.fill(10);
arr[2] = 15;
arr.print();
std::cout << "Max value in the array: " << arr.findMax() << std::endl;
return 0;
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。