设计一个整型数组类,能够通过[]下标的形式访问数组的某个元素,如果越界输出错误提示。(pushback方法可以在数组的末尾增加数据,此时如果数组容量不足,能够自动扩容,确保正确保存数据。)
时间: 2024-05-07 08:16:08 浏览: 9
以下是一个简单的整型数组类的实现,包括了[]下标访问和自动扩容的功能。
```cpp
#include <stdexcept>
class IntArray {
public:
IntArray(int size = 0) : m_size(size), m_capacity(size) {
if (size > 0) {
m_data = new int[size];
} else {
m_data = nullptr;
}
}
IntArray(const IntArray& other) : m_size(other.m_size), m_capacity(other.m_capacity) {
m_data = new int[m_capacity];
for (int i = 0; i < m_size; i++) {
m_data[i] = other.m_data[i];
}
}
~IntArray() {
delete[] m_data;
}
IntArray& operator=(IntArray other) {
swap(*this, other);
return *this;
}
int size() const {
return m_size;
}
int capacity() const {
return m_capacity;
}
int& operator[](int index) {
if (index < 0 || index >= m_size) {
throw std::out_of_range("Index out of range");
}
return m_data[index];
}
void pushback(int value) {
if (m_size == m_capacity) {
int new_capacity = (m_capacity == 0) ? 1 : m_capacity * 2;
int* new_data = new int[new_capacity];
for (int i = 0; i < m_size; i++) {
new_data[i] = m_data[i];
}
delete[] m_data;
m_data = new_data;
m_capacity = new_capacity;
}
m_data[m_size++] = value;
}
friend void swap(IntArray& first, IntArray& second) {
using std::swap;
swap(first.m_size, second.m_size);
swap(first.m_capacity, second.m_capacity);
swap(first.m_data, second.m_data);
}
private:
int m_size;
int m_capacity;
int* m_data;
};
```
使用示例:
```cpp
IntArray arr(3);
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr.pushback(4);
std::cout << "size: " << arr.size() << ", capacity: " << arr.capacity() << std::endl; // size: 4, capacity: 6
std::cout << arr[0] << ", " << arr[1] << ", " << arr[2] << ", " << arr[3] << std::endl; // 1, 2, 3, 4
try {
arr[4] = 5; // Index out of range
} catch (std::exception& e) {
std::cout << e.what() << std::endl;
}
```