【发布时间】:2020-07-24 20:56:31
【问题描述】:
我正在尝试在犰狳中使用稀疏矩阵功能,但在序列化它时遇到了一些麻烦。我正在处理的矩阵非常大,并且在组件中大部分为零,因此使用 sp_mat 是有意义的。代码如下:
#include <iostream>
#include <fstream>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <armadillo>
#include <boost/serialization/split_member.hpp>
BOOST_SERIALIZATION_SPLIT_FREE(arma::sp_mat)
namespace boost {
namespace serialization {
template<class Archive>
void save(Archive & ar, const arma::sp_mat &t, unsigned int version)
{
ar & t.n_rows;
ar & t.n_cols;
const double *data = t.memptr();
for(int K=0; K<t.n_elem; ++K)
ar & data[K];
}
template<class Archive>
void load(Archive & ar, arma::sp_mat &t, unsigned int version)
{
int rows, cols;
ar & rows;
ar & cols;
t.set_size(rows, cols);
double *data = t.memptr();
for(int K=0; K<t.n_elem; ++K)
ar & data[K];}
}}
int main() {
arma::mat C(3,3, arma::fill::randu);
C(1,1) = 0; //example so that a few of the components are u
C(1,2) = 0;
C(0,0) = 0;
C(2,1) = 0;
C(2,0) = 0;
arma::sp_mat A = arma::sp_mat(C);
std::ofstream outputStream;
outputStream.open("bin.dat");
std::ostringstream oss;
boost::archive::binary_oarchive oa(outputStream);
oa & A;
outputStream.close();
arma::sp_mat B;
std::ifstream inputStream;
inputStream.open("bin.dat", std::ifstream::in);
boost::archive::binary_iarchive ia(inputStream);
ia & B;
return 0;
}
当前的问题是 sp_mat 没有 mempr() 成员,因此序列化已完成的组件,例如第 10-12 行不适用于 sp_mat。我很好奇是否有人知道解决方法?我觉得奇怪的是,当我单独打印 A 的所有组件时,即使稀疏矩阵忽略了零,即使零仍在内存中。例如。我打印了 A(1,1),得到了 0。这也是打印时 A 的样子:
[matrix size: 3x3; n_nonzero: 4; density: 44.44%]
(1, 0) 0.2505
(0, 1) 0.9467
(0, 2) 0.2513
(2, 2) 0.5206
【问题讨论】:
标签: c++ serialization boost sparse-matrix