【问题标题】:Are stacks and queues passed like arrays in C++?堆栈和队列是否像 C++ 中的数组一样传递?
【发布时间】:2020-10-24 21:29:39
【问题描述】:

我想问这个是因为我们可以在不传递引用的情况下更改传递给函数的数组的内容,但它与堆栈和队列不同。你能告诉这两者是如何传递给 然后运行。

【问题讨论】:

  • 无论您选择如何通过它们,它们都会被通过。
  • 您认为数组如何作为参数传递?你的接受数组的函数是什么样的?
  • 您实际上并没有传递数组,而是传递了一个指向其第一个元素的指针。

标签: c++ arrays stack queue


【解决方案1】:

您需要了解 Array 基本上是一系列可通过指针直接访问的内存位置。 与此相反,stacksqueues 是您实例化的容器。


void foo(std::stack<int> st) { //pass by value
//whatever
}

void foo(std::stack<int>& st) { //pass by reference
//whatever
}

void foo(std::stack<int>* st) { //pass by pointer
//whatever
}

std::stack<int> stack; //instantiation
foo(stack); //calling the function
foo(&stack); //when you need to pass by pointer (never used)

【讨论】:

  • 嗨 d4rk4ng31,如果你通过指针(&stack)传递它。它是否指向数组的顶部?还是底部?
  • @Fernand &amp;stack 指向堆栈对象本身,而不是它的任何元素。
猜你喜欢
  • 2020-06-12
  • 2013-09-30
  • 2020-04-22
  • 1970-01-01
  • 2011-04-08
  • 2021-11-08
  • 1970-01-01
  • 1970-01-01
  • 2013-09-18
相关资源
最近更新 更多