C++,堆栈和结构的指针

C++, stack and pointers of struct

本文关键字:指针 结构 堆栈 C++      更新时间:2023-10-16

您好,我在堆栈中的结构上的指针有问题。

我有一堆结构:

stack<Somethink*> stack1;

我想推动和弹出"Somethink"的阵列

void Search(Somethink* array_Somethink, int s, int d,) {
stack1.push(&(array_Somethink[s]));  // 
while (stack1.size() != 0) {
    int  i = 0;
    array_Somethink[i] = *(stack1.pop()); // this return a error
    i++;
   }
}

我希望有人能给我一个提示,如何正确地从这个堆栈中推送和弹出

谢谢:D

void Search(Somethink* array_Somethink, int s, int d,) {
stack1.push(&(array_Somethink[s]));  // 
while (!stack1.empty()) {
    int  i = 0;
    array_Somethink[i] = *(stack1.top());
    stack1.pop();
    i++;
   }
}

我修改后的代码假设,您"拥有"指向堆栈上其他地方元素的指针。如果不是这种情况,您将在此处以内存泄漏结束,因为堆栈中的指针变成悬空对象(泄漏)。

为了避免内存泄漏的可能性,在这里,如果您使用 std::shared_ptr<Somethink> 而不是原始指针,这可能是一个好主意。然后,您的堆栈将成为std::stack< std:shared_ptr<Somethink> >

有关 std::stack 操作empty(),pop(),top()的详细信息,请参阅通常位置的std::stack

在那里,你会发现这样的解释:

标准::堆栈::顶部 C++ 容器库 std::stack 引用顶部(); const_reference top() 常量; 返回对堆栈中顶部元素的引用。这是最近推送的元素。此元素将在调用 pop() 时删除。有效地调用 c.back()。

top将返回指向该结构的指针,并且您正在尝试将其分配给该结构的实例。基本上,您正在尝试分配一个指针,以SomethinkSomethink数组中的某个位置