带有函数对象的std :: for_each

时间:2017-07-24 20:01:28

标签: c++ algorithm

以下代码产生了一个非常奇怪的输出,我不明白为什么。 它应该是我其他测试程序的一个非常原始的基准。无论执行什么可执行文件作为cmd行参数执行几次并计算时钟周期,然后计算mean和stddev(好吧,还没有完全实现,但你明白了)。

#include <algorithm>
#include <cmath>
#include <ctime>
#include <iostream>
#include <numeric>
#include <vector>

class SRS{
public:
  SRS(double p1):mean(p1), srs(0.0){std::cout << this->mean << std::endl;} //DEBUG
  double operator()(unsigned p1){
    this->srs += std::pow(this->mean - (double)p1, 2.0);
    std::cout << p1 << "    " << this->srs << std::endl; //DEBUG
  }
  double getSrs(){
    return this->srs;
  }
private:
  double mean;
  double srs;
};

int main(int argc, char* argv[]){
  unsigned nCyc;
  if(argc<3){nCyc=1000;}else{nCyc=std::stoi(argv[2]);}
  std::vector<clock_t> c{};
  for(unsigned u = 0; u<nCyc; u+=1){
    clock_t t = clock();
    system(argv[1]); //this is stupid and dangerous
    t = clock() - t;
    c.push_back(t);
  }
  clock_t clkSum = std::accumulate(c.begin(), c.end(), 0);
  double clkMean = (double)clkSum / (double)nCyc;
  SRS srs(clkMean);
  std::for_each(c.begin(), c.end(), srs);
  std::cout << "The program ran for " << clkMean << " +/- " << srs.getSrs() << " clock cycles" << std::endl;

  return 0;
}

让我感到困惑的是,srs.getSrs()总是返回由c'tor分配给SRS :: srs的任何值(这里是0.0)。 在创建流的输出之后评估std :: for_each还是在执行后std :: for_each将函数对象恢复为以前的状态?

1 个答案:

答案 0 :(得分:8)

std::for_each的谓词参数是一个值,这意味着该算法使用作为参数传递的仿函数的副本。如果要检查其状态,可以使用返回给您的副本:

SRS ret = std::for_each(c.begin(), c.end(), srs);
std::cout << "The program ran for " << clkMean 
          << " +/- " << ret.getSrs() << " clock cycles" << std::endl;