gpt4 book ai didi

C++ 动态、基于数组的整数堆栈

转载 作者:行者123 更新时间:2023-11-30 05:46:54 24 4
gpt4 key购买 nike

我刚刚开始学习 C++ 编程,为了锻炼我找到了这个任务。我必须编写一个动态的、基于数组的整数堆栈。这是我到目前为止所得到的。

    #include <iostream>

using namespace std;


class DynamicIntegerStack
{
private:
int *bottom_;
int *top_;
int size_;
public:
DynamicIntegerStack(int n = 20){
bottom_ = new int[n];
top_ = bottom_;
size_ = n;
}

int getSize(){ return size_; }

void push(int c){
if (!full()){
*top_ = c;
top_++;
}
else{
resize(size_ * 2);
*top_ = c;
top_++;
}
}

void resize(int newSize){
//Allocate new array and copy in data
int *newArray = new int[newSize];
memcpy(newArray, bottom_, size_);

// Set the top to the new array
top_ = newArray + (top_ - bottom_);

// Delete old array
delete[] bottom_;

// Update pointers and size
bottom_ = newArray;
size_ = newSize;

cout << "array has been resized" << endl;
}

int num_items() {
return (top_ - bottom_);
}
char pop(){
top_--;
return *top_;
}
int full() {
return (num_items() >= size_);
}
int empty() {
return (num_items() <= 0);
}
void print(){
cout << "Stack currently holds " << num_items() << " items: ";
for (int *element = bottom_; element<top_; element++) {
cout << " " << *element;
}
cout << "\n";
}
~DynamicIntegerStack(){ // stacks when exiting functions
delete[] bottom_;
}
};
int main(){
DynamicIntegerStack s(5);
s.print(); cout << "\n";
s.push(1); s.push(3); s.push(5); s.push(10); s.push(15);
s.print(); cout << "\n";
s.push(20);
s.print(); cout << "\n";
cout << "Popped value is: " << s.pop() << "\n";
s.print(); cout << "\n";
s.push(30);
s.print(); cout << "\n";
s.pop();
s.pop();
s.print(); cout << "\n";
while (!s.empty()) s.pop();
if (s.num_items() != 0) {
cout << "Error: Stack is corrupt!\n";
}
s.print(); cout << "\n";
// destructor for s automatically called
system("pause"); // execute M$-DOS' pause command
return 0;
}

它工作正常,直到数组已满并且我调整它的大小。之后它开始打印而不是整数。 DynamicIntegerStack

预先感谢您的帮助。

最佳答案

当您使用memcpy 时,您正在复制的内存大小必须以字节为单位给出。

因此,您必须将 sizeof(int) 与您的 n 相乘。

关于C++ 动态、基于数组的整数堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28741516/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com