【发布时间】:2014-05-02 02:15:47
【问题描述】:
我试图在结构类型的序列化和反序列化之后比较两个映射。它给了我错误 - ““MyExample”中的错误:检查 e1_i1->second == e2_i1->second failed”。
我不知道下面的代码有什么问题:
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/map.hpp>
#include <boost/serialization/shared_ptr.hpp>
struct A
{
public:
std::string oldname;
std::string newname;
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive &ar, const unsigned int version)
{
ar & oldname;
ar & newname;
}
};
struct Example
{
public:
bool check;
std::map<std::string,boost::shared_ptr<A>> Atype;
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive &ar, const unsigned int version)
{
ar & check;
ar & Atype;
}
};
void set_data(boost::shared_ptr<A> e)
{
e->oldname="a";
e->newname="b";
}
void set_data(Example *e)
{
e->check=false;
// to initialize e->Atype
boost::shared_ptr<A> a1 (new A());
set_data(a1);
e->Atype.insert(std::make_pair("a",a1));
}
void compare_data(std::map<std::string,boost::shared_ptr<A>> e1,std::map<std::string,boost::shared_ptr<A>> e2)
{
// because it is of type map, it may be not in proper order
typedef std::map<std::string,boost::shared_ptr<A>>::const_iterator i1;
i1 e1_i1= e1.begin();
i1 e2_i1 =e2.begin();
while ( e1_i1 != e1.end() && e2_i1 != e2.end())
{
BOOST_CHECK( e1_i1->first == e2_i1->first);
const std::string &key = e1_i1->first;
e2_i1 =e2.find(key);
BOOST_CHECK(e1_i1->second == e2_i1->second);
e1_i1++;
e2_i1++;
}
}
void compare_data(Example *e1,Example *e2)
{
BOOST_CHECK(e1->check == e2->check);
// need to compare e1->Atype with e2->Atype
compare_data(e1->Atype,e2->Atype);
}
BOOST_AUTO_TEST_CASE(MyExample)
{
boost::archive::text_oarchive ao(std::cout);
Example c;
set_data(&c);
const Example & oc=c;
ao << oc;
std::stringstream ss;
boost::archive::text_oarchive oa(ss);
oa << oc;
boost::archive::text_iarchive ia(ss);
Example d;
ia >> d;
compare_data(&c,&d);
}
我已确保包含所有头文件,但这里我没有包含所有头文件。 真的不知道上面的代码有什么问题,要么数据的设置值不正确,要么比较可能有误。
我尝试过的初始化地图的不同方法:
// e->Atype=map_list_of ("a",a1);
// e->Atype.insert(std::make_pair("a",a1));
// e->Atype.insert(std::map<std::string,boost::shared_ptr<A>>::value_type("a",a1));
// e->Atype["a"]=a1;
谢谢,
【问题讨论】:
-
我尝试了不同类型的地图初始化......但仍然存在上述代码中给出的问题。
-
下面的链接也没有帮助 - stackoverflow.com/questions/1676781/…
-
您是否使用调试器检查过地图/共享指针的内容?
-
@dutt - 是的.. 问题出在 BOOST_CHECK(e1_i1->second == e2_i1->second);两者都显示不同的地址位置而不是寻找价值..
-
你如何从 shared_ptr 中获取值?
标签: c++ serialization boost boost-serialization