• 主页
• 问答

# 基于boost::multi_array的矩阵相乘

richbirdandy 2008-09-09 03:07:35

``````
#include <iostream>
#include "boost/multi_array.hpp"
using namespace std;

typedef boost::multi_array<int, 2> matrix;

matrix matrix_multiply(matrix& a,matrix& b)
{
matrix::index row=a.shape()[0];
matrix::index col=b.shape()[1];
matrix c(boost::extents[row][col]);

for (matrix::index i=0; i!=a.shape()[0]; ++i)
for (matrix::index j=0; j!=b.shape()[1]; ++j)
for (matrix::index k=0; k!=a.shape()[1]; ++k)
c[i][j]+=a[i][k]*b[k][j];

return c;
}

void print(const matrix& m)
{
for (matrix::index i=0; i!=m.shape()[0]; cout<<endl,++i)
for (matrix::index j=0; j!=m.shape()[1]; ++j)
cout<<m[i][j]<<" ";
}

int main() {

int values[] = {
0, 1, 2,
3, 4, 5
};
const int values_size = 6;
matrix A(boost::extents[2][3]);
matrix B(boost::extents[3][2]);
A.assign(values,values + values_size);
B.assign(values,values + values_size);

cout<<"matrix A"<<endl;
print(A);
cout<<endl;cout<<"*"<<endl;cout<<"matrix B"<<endl;
print(B);
cout<<endl;cout<<"="<<endl;cout<<"matrix C"<<endl;
print(matrix_multiply(A,B));
cout<<endl;

return 0;
}
``````

...全文
207 点赞 收藏 5

5 条回复

up一下，还没开始用boost这个东西呢

wudeshou82666 2008-09-09

wangdeqie 2008-09-09

richbirdandy 2008-09-09

richbirdandy 2008-09-09
[Quote=引用 2 楼 wangdeqie 的回复:]

[/Quote]

C++ 语言

5.9w+

C++ 语言相关问题讨论，技术干货分享，前沿动态等