以下是稀疏矩阵的测试程序,以及序列化的过程,对于序列化过程,可以参照MSDN里面色实例。
1: // sparse.cpp : 定义控制台应用程序的入口点。
2: //
3: 4: #include "stdafx.h"
5: #include <conio.h>6: #using <system.dll>
7: #using <system.messaging.dll>
8: #using <System.Runtime.Serialization.Formatters.Soap.dll>//这个里面包含二进制流序列化
9: 10: using namespace System;
11: using namespace System::IO;
12: using namespace System::Runtime::Serialization::Formatters::Binary;
13: 14: typedef unsigned short int uint;
15: 16: //三元组
17: typedef struct Point
18: {19: uint x;//行号 x坐标
20: uint y;//列号 y坐标
21: Byte value;
22: Byte val; //type类型,T的类型可变。模板函数指的是函数模板的一种实例化,具体化(函数模板的实例化)。
23: } Point;24: //稀疏矩阵声明
25: 26: [Serializable]27: ref class SparseMatrix //稀疏矩阵类 模板类 是一种具体的、实实在在的函数的定义(类模板的实例化)。
28: {29: public:
30: SparseMatrix(int maxt); //初始化,最大结构体的长度,注:这个是可变的。用一个全局变量来表示即可。初始化为非零元素的最大个数。
31: ~SparseMatrix(); //析构函数。释放资源
32: void Print()
33: {34: Console::WriteLine( "rows = ‘ {0}‘", rows );
35: Console::WriteLine( "cols = ‘ {0}‘", cols );
36: }37: private:
38: Point* point; 39: uint rows; //稀疏矩阵的行号
40: uint cols; //稀疏矩阵的列号
41: uint terms; //稀疏矩阵中非零元素的个数
42: }; //存储非零元素的个数及一个表示矩阵行数、列数三元组,这个三元组主要是为了存储结构体数组而建立的。
43: SparseMatrix ::SparseMatrix(int maxt)
44: { 45: terms = maxt;46: point = new Point[terms];
47: rows = 0; 48: cols = 0; 49: } 50: SparseMatrix ::~SparseMatrix() 51: {52: if (point!=NULL)
53: { 54: delete[] point; 55: } 56: } 57: 58: int main()
59: {60: //Creates a new TestSimpleObject object.
61: SparseMatrix^ obj = gcnew SparseMatrix(50);62: Console::WriteLine( "Before serialization the Object* contains: " );
63: obj->Print();64: //下面是序列化过程
65: Stream^ stream = gcnew MemoryStream(); 66: BinaryFormatter^ formatter = gcnew BinaryFormatter(); 67: formatter->Serialize( stream, obj ); 68: stream->Position = 0; 69: array<Byte>^ buffer = gcnew array<Byte>(stream->Length);70: stream->Read( buffer,0,sizeof(buffer)); //使用 Read 读取数据块
71: stream->Flush(); 72: stream->Close(); 73: obj = nullptr; 74: getch();75: return 0;
76: } 77: 原文:http://www.cnblogs.com/zhuxuekui/p/3552701.html