gpt4 book ai didi

c++ - 如何序列化 Armadillo 的 vector

转载 作者:搜寻专家 更新时间:2023-10-31 01:34:16 24 4
gpt4 key购买 nike

如何序列化 arma::Col ?下面是 MWE 和错误输出。

MWE:

#include <boost/mpi/environment.hpp>
#include <boost/mpi/communicator.hpp>
#include <iostream>
#include "armadillo"

namespace mpi = boost::mpi;

struct S
{
int i;
arma::Col<double>::fixed<3> cvector;

friend class boost::serialization::access;

template<class Archive>
void serialize(Archive& ar, const unsigned int version)
{
ar& i;
ar& cvector;
}
};

int main()
{
mpi::environment env;
mpi::communicator world;

S s;

if (world.rank() == 0)
{
s.cvector[0] = 2;
s.cvector[1] = 2;
world.send(1, 0, s);
}
else
{
world.recv(0, 0, s);
std::cout << s.cvector[0] << std::endl;
std::cout << s.cvector[1] << std::endl;
}

return 0;
}

错误输出(跳过“required from”内容):

error: ‘class arma::Col<double>::fixed<3ull>’ has no member named ‘serialize’; did you mean ‘set_size’?
t.serialize(ar, file_version);

编辑: This帖子似乎与我的问题有关,不幸的是它没有得到回答。

最佳答案

这里问题的真正症结在于,您想向各种 Armadillo 对象添加一个 serialize() 成员函数,但这似乎不可能...除了谢谢在 Armadillo 中巧妙地使用预处理器,它是!

看看 Mat_bones.hppCol_bones.hpp...您会在 Mat< 的类定义中看到类似这样的内容Col:

public:

#ifdef ARMA_EXTRA_COL_PROTO
#include ARMA_INCFILE_WRAP(ARMA_EXTRA_COL_PROTO)
#endif

当我发现这个时,我非常高兴,因为现在我可以做一些事情,比如定义一个名为 Mat_extra_bones.hpp 的文件:

//! Add a serialization operator.
template<typename Archive>
void serialize(Archive& ar, const unsigned int version);

然后是 Mat_extra_meat.hpp:

// Add a serialization operator.
template<typename eT>
template<typename Archive>
void Mat<eT>::serialize(Archive& ar, const unsigned int /* version */)
{
using boost::serialization::make_nvp;
using boost::serialization::make_array;

const uword old_n_elem = n_elem;

// This is accurate from Armadillo 3.6.0 onwards.
// We can't use BOOST_SERIALIZATION_NVP() because of the access::rw() call.
ar & make_nvp("n_rows", access::rw(n_rows));
ar & make_nvp("n_cols", access::rw(n_cols));
ar & make_nvp("n_elem", access::rw(n_elem));
ar & make_nvp("vec_state", access::rw(vec_state));

// mem_state will always be 0 on load, so we don't need to save it.
if (Archive::is_loading::value)
{
// Don't free if local memory is being used.
if (mem_state == 0 && mem != NULL && old_n_elem > arma_config::mat_prealloc)
{
memory::release(access::rw(mem));
}

access::rw(mem_state) = 0;

// We also need to allocate the memory we're using.
init_cold();
}

ar & make_array(access::rwp(mem), n_elem);
}

那么,在你的程序中,你需要做的就是

#define ARMA_EXTRA_MAT_PROTO mat_extra_bones.hpp
#define ARMA_EXTRA_MAT_MEAT mat_extra_meat.hpp

serialize() 函数将成为 Mat 类的成员。您可以轻松地将此解决方案应用于其他 Armadillo 类型。

事实上,这正是 mlpack 库 ( http://www.mlpack.org/) 所做的,所以如果您有兴趣,可以仔细看看我在那里实现的确切解决方案:

https://github.com/mlpack/mlpack/tree/master/src/mlpack/core/arma_extend

关于c++ - 如何序列化 Armadillo 的 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39890640/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com