c++ - 每 n 次迭代将输出写入文件

标签 c++ count iteration

大家好, 这是一个包的以下代码:

for (int iter = 0; iter < flags.total_iterations_; ++iter) {
std::cout << "Iteration " << iter << " ...\n";
if (flags.compute_likelihood_ == "true") {
  double loglikelihood = 0;
  for (list<LDADocument*>::const_iterator iterator = corpus.begin();
       iterator != corpus.end();
       ++iterator) {
    loglikelihood += sampler.LogLikelihood(*iterator);
  }
  std::cout << "Loglikelihood: " << loglikelihood << std::endl;
}
sampler.DoIteration(&corpus, true, iter < flags.burn_in_iterations_);
}
accum_model.AverageModel(
  flags.total_iterations_ - flags.burn_in_iterations_);

FreeCorpus(&corpus);

std::ofstream fout(flags.model_file_.c_str());
accum_model.AppendAsString(word_index_map, fout);

return 0;

我想以每 20 次迭代的方式对此进行调整,我想编写一个文件来存储 fout 的结果。我实际上是 python 代码编码的初学者。由于包中有 C++ 代码,我不知道在哪里输入什么。

我理解这样的逻辑:

必须有一个计数器来计算迭代次数,每进行 20 次迭代,必须创建一个文件并将 fout 的结果保存在该文件中。对于每 20 次迭代,我需要创建新文件,因为我不希望为了分析目的而覆盖内容。

请帮助我,因为我是一个对 C++ 完全一窍不通的新手。提前致谢!

最佳答案

试试这个:

    for (int iter = 0; iter < flags.total_iterations_; ++iter) { 
      double loglikelihood = 0;
      std::cout << "Iteration " << iter << " ...\n";
      if(iter%20==0) {
         const char *path1 = "Your path to the files" 
         std::ofstream llh_file;
         std::ofstream myfile;
         std::string result;
         char numstr[30];
         sprintf(numstr, "%d", iter);
         result = path1 + std::string (numstr) + ".txt";
         myfile.open(result.c_str());
         model.AppendAsString(myfile);   
         myfile.close();   

关于c++ - 每 n 次迭代将输出写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29536142/

相关文章:

javascript - 按频率排序数组

php - 在 PHP 中检测数组的 "actual"结尾

c++ - 部分特化模板作为特征成员类型

C++,cin,直到不再使用 while 循环在线输入

MySQL - 按表中的重复值进行分组以进行计数并将输出保存在另一个表中

MySQL COUNT() 或 SUM()

excel - 幂法 - 非收敛系统

MATLAB 每次迭代更改矩阵的名称

c++ - 从 CPPRest 库(即 casablanca)获得的结果中提取基本 STL 字符串?

C++ - For 循环不工作