什么可以用来在 C++ 中保存像图形这样的结构(Python pickle 等价物)
what can be used to save structures like graphics in c ++ (Python pickle equivalent)
我有一个带有边和顶点的图结构。我想像 python 中的酸洗一样序列化并保存它。我可以用它做什么?
C++ 本身不支持通用序列化。
所以,你有 3 个选择:
- 在 google 中搜索 "c++ serialization library" 并使用它
- 自己写一个class
- 使用 JSON
这样的标准
对于 2.:
通常情况下,图表的所有数据都集中在一个 class 中。您唯一需要做的就是为您的 class.
覆盖插入器 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;
}
我有一个带有边和顶点的图结构。我想像 python 中的酸洗一样序列化并保存它。我可以用它做什么?
C++ 本身不支持通用序列化。
所以,你有 3 个选择:
- 在 google 中搜索 "c++ serialization library" 并使用它
- 自己写一个class
- 使用 JSON 这样的标准
对于 2.:
通常情况下,图表的所有数据都集中在一个 class 中。您唯一需要做的就是为您的 class.
覆盖插入器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;
}