【问题标题】:inserting average of data into a vector将数据的平均值插入向量中
【发布时间】:2012-05-05 16:05:09
【问题描述】:

我在测试中有以下数据:

2011-01-03      2116    
2011-01-03      2120    
2011-01-04      2116    
2011-01-04      2115

以及以下代码:

std::map<std::string, std::vector<double> >::iterator tk = test.begin();
std::vector<double>tmp;

std::copy(tk->second.begin(), tk->second.end(), std::back_inserter(tmp));

上面的代码tmp包含:

2116
2120
2116
2115

但是,我想将每个日期的tk-&gt;second 平均值插入tmp。我必须将我的 back_inserter 写入循环吗?

【问题讨论】:

    标签: c++ stl stdvector


    【解决方案1】:
    for(auto it = test.begin(); it != test.end(); it++)
    {
      double sum = 0.0;
      int count = 0;
      for(auto it2 = it->second.begin(); it2 != it->second.end(); it2++, count++)
      { 
        sum += *it2;
      }
      tmp.push_back(sum / count);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多