带有指针的动态堆栈结构
dynamic stack structures with pointers
我正在构建一个动态堆栈,它需要一个带有指向数组的指针的结构。
class studentstack
{
private:
struct StackNode
{
int ID;
string Name;
string Address;
StackNode * next; // pointer to the next node
double * scores; // pointer to the arry of scores
};
当我的主文件中我试图用双精度填充数组然后将其传递给一个函数时,当我什么都不做时,似乎传递正确。 正确的方法是什么?
int main()
{
studentstack s;
string name;
int id;
string address;
double score;
for(int x =0; x<20; x++)
{
cout << "nNew Student Name: ";
cin >> name;
cout << "nID: ";
cin >> id;
cout << "nAddress: ";
cin >> address;
double scoresArr[10];
for(int z=0; z<10; z++)
{
cout << "nStudent Score " << z+1 << ": ";
cin >> score;
scoresArr[z] = score;
}
s.push(name, id, address, scoresArr);
推:
void studentstack::push(string name, int id, string address, double scoresArr)
{
StackNode *newStudent; // To point to the new Student
newStudent = new StackNode;
newStudent-> ID = id;
newStudent-> Name = name;
newStudent-> Address = address;
newStudent-> scores = scoresArr;
// If there are no nodes in the stack
if (isEmpty())
{
top = newStudent;
newStudent->next= NULL;
}
else // or add before top
{
newStudent->next = top;
top = newStudent;
}
}
技术问题在于您尚未显示的代码(当我编写本文时),即push
代码。
但是,有一个简单的解决方案,无论您的push
如何搞砸事情,它都会起作用。
也就是说,使用 std::vector
而不是动态分配的原始数组。
或者,只需在每个节点中使用固定大小的原始数组。
就此而言,std::list
会比DIY链表更好,但大概这个练习的重点在于熟悉链表结构。对每个节点中的阵列使用 std::vector
不会干扰该目标。但请记住,在现代C++无论问题是什么,自己创建链表都很少是一个好的解决方案 - 相反,使用标准库容器类和/或来自第三方库的容器类。
相关文章:
- 在什么情况下,两个堆栈分配的结构对象的 this 点指向同一个地址?
- 如何在C++中为堆栈动态创建结构?
- 使用带有链表的堆栈数据结构将中缀转换为后缀
- 我的堆栈和库存清单程序的结构有什么问题?
- 当我尝试为结构分配新指针时出现堆栈溢出错误
- 在C++中使用链表的堆栈实现中,访问结构体headNode成员count和top会导致运行时错误
- C++ 堆栈推送方法不会将结构推送到堆栈上,只是返回 0
- 是否可以检查存储在堆栈上的单词是否是回文,而C++中没有任何附加数据结构
- 递归如何使用堆栈数据结构
- 构建模板 使用矢量 c++ 的堆栈结构
- 比较堆栈数据结构 c++
- 使用提升库在队列和堆栈数据结构上保存和加载数据时出错
- Boost::序列化存储结构时的堆栈溢出错误
- 堆栈(数据结构)实现
- 如何在C 中的标准堆栈中推动结构类型变量
- 您如何声明类型结构的堆栈?在C 中
- 使用boost::序列化递归图结构时,如何防止堆栈溢出
- 将记录推送到数据结构中的堆栈
- 带有指针的动态堆栈结构
- 分配过大的堆栈结构是未定义的行为吗