c++ - 什么可用于在 c ++ 中保存图形等结构(Python pickle 等价物)
问题描述
我有一个带有边和顶点的图结构。我想像在 python 中酸洗一样序列化并保存它。我可以用来做什么?
解决方案
C++ 本身不支持通用序列化。
因此,您有 3 个选项:
- 在 google 中搜索“c++ 序列化库”并使用它
- 自己写一堂课
- 使用 JSON 等标准
对于 2.:
通常,您在一个类中拥有图表的所有数据。您唯一需要做的就是覆盖类的插入器operator <<
和提取器operator
。
我给你一个简单的例子:
#include <iostream>
#include <sstream>
#include <string>
#include <fstream>
#include <vector>
#include <iterator>
#include <algorithm>
std::istringstream testFile(R"(1 2 3
10 11 12)");
struct Graph
{
int x,y; // Some example data
int numberOfEdges; // The number of elements in the vector
std::vector<int> edges; // An array of data
// Serializing. Put the data into a character stream
friend std::ostream& operator << (std::ostream& os, Graph& g) {
os << g.x << ' ' << g.y << ' '<< g.numberOfEdges << '\n';
std::copy(g.edges.begin(), g.edges.end(), std::ostream_iterator<int>(os, " "));
return os;
}
// Deserializing. Get the data from a stream
friend std::istream& operator >> (std::istream& is, Graph& g) {
is >> g.x >> g.y >> g.numberOfEdges;
std::copy_n(std::istream_iterator<int>(is), g.numberOfEdges, std::back_inserter(g.edges));
return is;
}
};
// Test program
int main(int argc, char *argv[])
{
Graph graph{};
// Read graph data from a file --> Deserializing
testFile >> graph;
// Put result to std::cout --> Serializing
std::cout << graph;
return 0;
}
推荐阅读
- php - 从另一个表插入到表中
- r - 与双引号“”相比,何时使用反引号''?
- wildcard - zsh 删除路径中带有通配符的子目录
- python - 如何解决超时错误,lambda python
- python-3.x - 如何在for循环中包含或包含python
- apache-spark - 在 spark sql 中组合 2 个映射列
- android - 使用Scenform将SceneView加载到片段后黑屏
- apache-spark - 在 PySpark 中将 CSV 文件从多个目录转换为镶木地板
- eclipse - Can we configure the Eclipse TFS plugin to require a work item on check in?
- regex - Using regex replacement in Sublime 3