动态堆栈内存重新分配

发布于 2024-12-08 04:11:46 字数 1238 浏览 0 评论 0原文

我对 C++ 相当陌生,对指针也很陌生。我目前正在处理一个堆栈,并试图在堆栈大小达到顶部时重新分配堆栈的内存,但是,我遇到了问题。我已经对 Google 和堆栈溢出进行了大量研究,并发现一些有用的信息,但由于我对堆栈和 C++ 很陌生,所以我仍然遇到问题。我希望一些聪明的人至少能为我指明正确的方向。

现在...这是我的代码。

#include <iostream>
#define STACKMAX 20
using namespace std;

template <class T> class StackTemplated {
private:
    int top;
    T   values[STACKMAX];
public:
    StackTemplated();
    void    push(T i);
    T       pop(void);
    bool    empty(void);
 }; 


template <class T> StackTemplated<T>::StackTemplated() {
    top = -1;
}

template <class T>void StackTemplated<T>::push(T i) {
if (top == STACKMAX - 1) {

    // reallocate top of stack. (this is the area I'm having issues)
    char * string1;
    string1 = (char *)calloc(STACKMAX, sizeof(char));

        if (top == STACKMAX - 1) {
            cout << "The stack didn't re-allocate.";
            exit(1);
        }

} else {
    top++;
    values[top] = i;
}
}   

 template <class T> T StackTemplated<T>::pop(void) {
if (top < 0) {
    printf("%", "Stack underflow!");
    exit(1);
} else {
    return values[top--];
}
}   

template <class T> bool StackTemplated<T>::empty() {
return (top == -1);
}

I'm fairly new to C++ and new to pointers as well. I'm currently working on a stack and was trying to reallocate the memory for the stack as the size of the stack reaches the top however, I'm running into issues. I've already done a lot of research both on Google and stack overflow and have found some information helpful but since I'm so new to stacks and C++ I'm still having issues. I was hoping some bright and intelligent people could at least point me in the right direction.

now... Here's my code.

#include <iostream>
#define STACKMAX 20
using namespace std;

template <class T> class StackTemplated {
private:
    int top;
    T   values[STACKMAX];
public:
    StackTemplated();
    void    push(T i);
    T       pop(void);
    bool    empty(void);
 }; 


template <class T> StackTemplated<T>::StackTemplated() {
    top = -1;
}

template <class T>void StackTemplated<T>::push(T i) {
if (top == STACKMAX - 1) {

    // reallocate top of stack. (this is the area I'm having issues)
    char * string1;
    string1 = (char *)calloc(STACKMAX, sizeof(char));

        if (top == STACKMAX - 1) {
            cout << "The stack didn't re-allocate.";
            exit(1);
        }

} else {
    top++;
    values[top] = i;
}
}   

 template <class T> T StackTemplated<T>::pop(void) {
if (top < 0) {
    printf("%", "Stack underflow!");
    exit(1);
} else {
    return values[top--];
}
}   

template <class T> bool StackTemplated<T>::empty() {
return (top == -1);
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

帅冕 2024-12-15 04:11:46

以下是我注意到的一些事情的列表:

  • STACKMAX 是一个常量。如果您要扩展堆栈,您将如何跟踪它当前的大小?
  • values 成员是一个固定大小的数组。如果不更改其声明和分配方式,您将无法动态更改其大小。
  • calloc() 使用您指定的字节数分配新的内存块。您需要以某种方式将现有堆栈复制到新的内存块中,并释放前一个堆栈。
  • 您在对 calloc() 的调用中仅分配 STACKMAX 字节。您可能希望按 sizeof T 缩放,以防 T 不是 char

一旦你解决了这些要点,就会有很多细节需要你解决。祝你好运。

Here's a list of a few things I noticed:

  • STACKMAX is a constant. If you're expanding the stack, how will you keep track of how big it currently is?
  • The values member is a fixed-size array. You won't be able to change the size of it dynamically without changing how this is declared and allocated.
  • calloc() allocates a new chunk of memory with the number of bytes you specify. You'll need to somehow copy the existing stack into the new memory block, and free the previous one.
  • You're allocating only STACKMAX bytes in the call to calloc(). You'll probably want to scale this by sizeof T, in case T is not a char.

There will be a lot of details for you to fix up once you address these major points. Good luck.

永言不败 2024-12-15 04:11:46

问题是您不想重新分配堆栈顶部。相反,您想要分配一个新的值数组,该数组足够大以容纳新值。另外,由于您需要重新分配数组,因此 values 应该是一个指针。

但是我们忘记这一切怎么样?如果我们使用 C++ 工作,让我们使用 C++ 提供的功能来让我们的生活更轻松。完成后,如果您确实觉得有必要,请尝试打开一切。

我所指的一件事是您对calloc 的使用。使用calloc是一个主意,特别是在使用模板时。问题是,由于 calloc 没有类型信息,因此它不会执行像调用构造函数这样基本的操作。构造函数在 OOP 中非常非常重要,因为它们保证对象在创建时的不变性。相反,请使用 new[] 关键字,例如

values = new T[STACKMAX];

这会分配 STACKMAX 长度的 T 数组。当然,正如 Greg 指出的那样,您应该重新考虑 STACKMAX 的使用,并改用变量。另外,values 不应该是静态数组,而应该是 T* 类型。

我提到的另一件事是,您实际上正在尝试实现一个根据需要动态增长的数组。在 C++ 中,我们将这样的结构称为向量。如果您使用向量,您的整个代码就会简化为

#include<iostream>
#include<vector>

using namespace std;

template<class T> class StackTemplated {
private:
    std::vector<T> vec;

public:
    StackTemplated() { } // the constructor is trivial; in fact, you can leave it out if you want
    void    push(T i);
    T       pop(void);
    bool    empty(void);
};

template<class T>
void StackTemplated<T>::push(T i) {
    vec.push_back(i);
}

template<class T>
T StackTemplate<T>::pop(void) {
    T top = vec.back();
    vec.pop_back();
    return top;
}

template<class T>
bool StackTemplate<T>::isEmpty(void) {
    return vec.size() == 0;
}

仅此而已。如果您可以使用现有的数据结构来实现新的数据结构,那么事情就会少很多。

一旦您真正熟悉向量的工作原理(并且网络上有大量解释/文档),然后尝试自己实现该功能。最重要的是,如果您确切地知道数据结构的行为方式,那么实现数据结构就会容易得多。

The problem is that you don't want to reallocate the top of the stack. Rather, you want to allocate a new array of values which is large enough to hold the new values. Also, since you need to reallocate the array, values should be a pointer.

But how about we forget all this. If we're working in c++, let's use what c++ offers us to make our lives easier. After that's done, then try open things up, if you really feel the need.

One of the things I'm referring to is your use of calloc. Using calloc is a bad idea, particularly when using templates. The problem is that since calloc has no type information, it won't do something as basic as calling a constructor. Constructors are very important in OOP, since they guarantee that an object's invariance when it is created. Instead, use the new[] keyword, like

values = new T[STACKMAX];

This allocates an array of T of STACKMAX length. Of course, as Greg points out, you should reconsider the use of STACKMAX, and use a variable instead. Also, values shouldn't be a static array, but should instead have type T*.

Another thing I was referring to is the fact that you are really trying to implement an array which grows dynamically as needed. In c++, we call such a structure a vector. If you use a vector, your entire code reduces to

#include<iostream>
#include<vector>

using namespace std;

template<class T> class StackTemplated {
private:
    std::vector<T> vec;

public:
    StackTemplated() { } // the constructor is trivial; in fact, you can leave it out if you want
    void    push(T i);
    T       pop(void);
    bool    empty(void);
};

template<class T>
void StackTemplated<T>::push(T i) {
    vec.push_back(i);
}

template<class T>
T StackTemplate<T>::pop(void) {
    T top = vec.back();
    vec.pop_back();
    return top;
}

template<class T>
bool StackTemplate<T>::isEmpty(void) {
    return vec.size() == 0;
}

That's all. It's a lot less hairy if you can use an existing data structure to implement the new data structure.

Once you get really comfortable with how a vector works (and there's plenty of explanations / documentation on the web), then try implementing the functionality yourself. Bottom line is, implementing a data structure is a lot easier if you know exactly how it's supposed to behave.

沉溺在你眼里的海 2024-12-15 04:11:46

我会声明你的值,

T* vaules;

然后使用 new 来创建它而不是 calloc。您需要跟踪堆栈的顶部及其大小。正如格雷格所说,当你增加堆栈时,请确保复制数据并清理旧数据。

I would declare your values like

T* vaules;

Then use new to create it not calloc. You will need to keep track of the top of the stack and size of it. As Greg says when you grow the stack make sure and copy data over and clean up the old one.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文