C++实现静态顺序表存储数据
时间: 2024-10-05 19:01:53 浏览: 48
在C++中,静态顺序表通常使用数组来实现,因为数组提供了一种连续的内存空间来存储数据,适合于存储固定大小的数据集合。静态顺序表的特点是在编译时确定其大小,不会动态增长或缩小。下面是一个简单的示例:
```cpp
template <typename T>
class StaticSequentialList {
private:
static const size_t CAPACITY; // 定义数组的最大容量
T elements[CAPACITY]; // 存储数据的数组
// 插入和删除操作需要检查索引是否超出界限
bool isValidIndex(size_t index) const {
return index >= 0 && index < CAPACITY;
}
public:
StaticSequentialList() : head_(0), tail_(0) {} // 构造函数初始化头部和尾部指针
// 添加元素到列表尾部
void push_back(const T& value) {
if (isValidIndex(tail_)) {
elements[tail_] = value;
++tail_;
} else {
// 如果已满,无法添加更多元素
throw std::runtime_error("Static list is full");
}
}
// 从列表头部获取并移除元素
T pop_front() {
if (isValidIndex(head_)) {
T result = elements[head_];
elements[head_] = T(); // 空值表示已移除
++head_; // 移动头部指针
return result;
} else {
throw std::runtime_error("Empty list");
}
}
// 访问指定位置的元素
const T& at(size_t index) const {
if (isValidIndex(index)) {
return elements[index];
} else {
throw std::out_of_range("Invalid index");
}
}
private:
size_t head_; // 首部指针
size_t tail_; // 尾部指针
};
// 特殊化模板常量,例如对于int类型的列表,容量可以设为100
template<> constexpr size_t StaticSequentialList<int>::CAPACITY = 100;
// 使用示例
int main() {
StaticSequentialList<int> lst;
lst.push_back(1);
lst.push_back(2);
try {
std::cout << lst.at(1) << '\n'; // 输出2
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << '\n';
}
return 0;
}
```
阅读全文
相关推荐


















