C++,堆栈和结构的指针
C++, stack and pointers of struct
您好,我在堆栈中的结构上的指针有问题。
我有一堆结构:
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
将返回指向该结构的指针,并且您正在尝试将其分配给该结构的实例。基本上,您正在尝试分配一个指针,以Somethink
到Somethink
数组中的某个位置
相关文章:
- 如何在 C# 中映射双 C 结构指针?
- 指针或结构的矢量
- MSVC将仅移动结构参数解释为指针
- 如何访问指针结构的成员变量?
- 如何将变量从变量传递到指针结构对象
- 如何在函数中检索指针结构
- C :变量的点地址至指针结构成员的地址
- C++指针结构不会被删除
- 初始化指针结构 - 内存中的外观
- C++指针结构和多线程
- c++中指针结构的运算符重载
- 为什么我不能转发声明指针结构?
- C# 如何定义新的指针结构
- 如何处理大型指针结构
- 我怎么能写一个函数的定义在模板类中声明返回指针结构对象
- 我如何编程指针结构或类变量在c++
- 具有指针结构的类所需的析构函数
- 为什么在非指针结构上进行类型转换会出现语法错误
- 语法:做binary_search (STL)排序向量的指针结构
- /a.检测到Glibc.out: munmap_chunk():无效指针- c++结构体的动态数组