我刚开始学习c++,只是学习堆栈推送和pop操作。我编写了一个小程序来推送和弹出堆栈中的一些元素。我的示例程序如下:
// stack::push/pop
#include <iostream> // std::cout
#include <stack> // std::stack
int main ()
{
std::stack<int> mystack;
for (int i=0; i<5; ++i) mystack.push(i);
std::cout << "Popping out elements...";
while (!mystack.empty())
{
std::cout << ' ' << mystack.top();
mystack.pop();
}
std::cout << '\n';
return 0;
} 但是现在我想将多个3*3矩阵推到堆栈上,希望使用mystack.top()获取每个矩阵,并使用mystack.pop操作弹出每个矩阵,并显示整个矩阵。如何为多个矩阵操作实现堆栈?
样本矩阵可以如下所示:
float A[3][3]={{1.0,2.0,3.0},{1.0,2.0,3.0},{1.0,2.0,3.0}};
float B[3][3]={{1.0,2.0,4.0},{1.0,5.0,3.0},{8.0,2.0,3.0}};发布于 2016-10-12 14:07:47
为此您可以使用std::array<std::array<float,3>,3>。普通数组不会自动复制,并且不符合存储在std::queue中的数据类型的需要。
std::array<std::array<float,3>,3> A {{{1.0,2.0,3.0},{1.0,2.0,3.0},{1.0,2.0,3.0}}};
std::array<std::array<float,3>,3> B {{{1.0,2.0,4.0},{1.0,5.0,3.0},{8.0,2.0,3.0}}};然后您可以简单地将堆栈定义为:
std::stack<std::array<std::array<float,3>,3>> myStack;为了使它更易读和更容易键入,您可以使用using或typedef
typedef std::array<float,3>,3> My3x3Matrix;
// ...
std::stack<My3x3Matrix> myStack;
myStack.push(A);
// ...
My3x3Matrix C = myStack.top();
myStack.pop();发布于 2016-10-12 14:10:29
为什么不直接使用Boost.MultiArray呢?
这个库中的类实现了一个公共接口,并将其形式化为一个通用编程概念。接口设计符合C++标准库容器设置的先例。Boost MultiArray是一种比现有的方案(尤其是N维数组的std::vector>公式)更有效、更方便地表达N维数组的方法。
array/doc/user.html
然后,听起来您想拥有下面的stack。
typedef boost::multi_array<int, 3> array_type;
std::stack<array_type> s;https://stackoverflow.com/questions/40000400
复制相似问题