C ++ - 数组元素在for循环中产生不同的值

时间:2014-07-30 16:16:13

标签: c++ arrays element addition

我在头文件(Uni.h)中声明了一个全局int数组,如下所示:

int durationArray[];

我的程序将运行并为数组分配元素(在本例中为2)。但是让我感到困惑的是,如果我使用for循环来显示它们,并且当我手动使用cout来显示它们时,数组元素会产生不同的值。这是我的代码:

cout << "durationArray at element 0 is :" << durationArray[0] << endl;
cout << "durationArray at element 1 is :" << durationArray[1] << endl;

int counting=2;             
for (int i=0; i<counting; i++)
{
    cout << "durationArray at element " << i << ": " << durationArray[i] << endl;
}

这是输出:

durationArray at element 0 is :3
durationArray at element 1 is :4


durationArray at element 0: 0
durationArray at element 1: 4

我的最终目标是获得数组元素的总和。但是,当我使用for循环遍历数组时,如果元素值错误,我该如何实现?我计划使用此代码进行添加:

for (int i=0; i<counting; i++)
    {
        sumofDuration+=durationArray[i];
    } 

1 个答案:

答案 0 :(得分:0)

使用std::accumulate就是这么简单:

#include <iostream>
#include <algorithm>

int main() {
  auto array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  std::cout << std::accumulate(std::begin(array), std::end(array), 0);
  return 0;
}

std::for_each带有lambda(如果累加器变得复杂则更灵活):

#include <iostream>
#include <algorithm>

int main() {
  auto array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  int sum { 0 };
  std::for_each(begin(array),end(array),[&](int n){
                        sum += n;  
    });
  std::cout << sum;
  return 0;
}