在c++中可以使用什么来保存图形等结构(相当于Python pickle)
我有一个带边和顶点的图结构。我想序列化并保存它,就像python中的酸洗一样。有什么用呢?C++本机不支持常规序列化 因此,您有3种选择: 在谷歌中搜索C++序列化库并使用它 自己为一个班级写 使用JSON之类的标准 第二条:在c++中可以使用什么来保存图形等结构(相当于Python pickle),c++,graph,pickle,C++,Graph,Pickle,我有一个带边和顶点的图结构。我想序列化并保存它,就像python中的酸洗一样。有什么用呢?C++本机不支持常规序列化 因此,您有3种选择: 在谷歌中搜索C++序列化库并使用它 自己为一个班级写 使用JSON之类的标准 第二条: 通常,图形的所有数据都在一个类中。您需要做的唯一一件事是覆盖插入器操作符。请分享您尝试过的内容。 #include <iostream> #include <sstream> #include <string> #include <
通常,图形的所有数据都在一个类中。您需要做的唯一一件事是覆盖插入器操作符。请分享您尝试过的内容。
#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;
}