I have a problem with loading/reading an
vector<vector< bitset<32> >
(called/typedef'ed as population in my code)
which it stored using the following code:
void genetic_algorithm::save_generation(population pop_to_save, string filename){
std::ofstream file(filename, std::ofstream::binary);
unsigned long n;
for(size_t i = 0; i < pop_to_save.size(); i++ )
{
if ( pop_to_save[i].size() > 0 )
{
n = pop_to_save[i][0].to_ulong();
const char* buffer = reinterpret_cast<const char*>(&n);
file.write(buffer, pop_to_save[i].size());
}
}
}
The thing i need is therefore a function that can load, i.e.:
population genetic_algorithm::load_generation(string filename){
// TODO
}
Best Regards,
Mathias.
EDIT
I have solved the problem on my own (with a bit of help from the comment) Here is the final code for any that might face the same problem:
void genetic_algorithm::save_generation(population pop_to_save, string filename){
std::ofstream file(filename, std::ofstream::binary);
unsigned long n;
for(size_t i = 0; i < pop_to_save.size(); i++ ) {
for (size_t j = 0; j < pop_to_save[i].size(); j++) {
n = pop_to_save[i][j].to_ulong();
file.write(reinterpret_cast<const char*>(&n), sizeof(n));
}
}
std::cout << "Saved population to: " << filename << '\n';
}
population genetic_algorithm::load_generation(string filename){
std::ifstream file(filename, std::ofstream::binary);
population loaded_pop (20, std::vector<bitset<32>> (394,0));
unsigned long n;
for(size_t i = 0; i < 20; i++ ) {
for (size_t j = 0; j < 394; j++) {
file.read( reinterpret_cast<char*>(&n), sizeof(n) );
loaded_pop[i][j] = n;
}
}
std::cout << "Loaded population from: " << filename << '\n';
return loaded_pop;
}