Created
November 5, 2012 09:45
-
-
Save shenfeng/4016355 to your computer and use it in GitHub Desktop.
serialize/deserialize vector<string>
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <vector> | |
using namespace std; | |
char* serialize(vector<string> &v, unsigned int *count) { | |
unsigned int total_count = 0; | |
for(int i = 0; i < v.size(); i++ ) { | |
// cout << v[i]<< endl; | |
total_count += v[i].length() + 1; | |
} | |
char *buffer = new char[total_count]; | |
int idx = 0; | |
for(int i = 0; i < v.size(); i++ ) { | |
string s = v[i]; | |
for (int j = 0; j < s.size(); j ++ ) { | |
buffer[idx ++] = s[j]; | |
} | |
buffer[idx ++] = 0; | |
} | |
*count = total_count; | |
return buffer; | |
} | |
void deserialize(vector<string> &restore, char* buffer, int total_count) { | |
for(int i = 0; i < total_count; i ++ ) { | |
const char *begin = &buffer[i]; | |
int size = 0; | |
while(buffer[i++]) { | |
size += 1; | |
} | |
restore.push_back(string(begin, size)); | |
} | |
} | |
int main(int argc, char ** argv) { | |
vector<string> v; | |
v.push_back("aaa"); | |
v.push_back("bbb"); | |
unsigned int total_count = 0; | |
char *buffer = serialize(v, &total_count); | |
vector<string> restore; | |
deserialize(restore, buffer, total_count); | |
for(int i = 0; i < restore.size(); i++ ) { | |
cout << restore[i]<< endl; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment