在C ++中使用do-while循环对向量元素求和

时间:2013-07-11 14:24:48

标签: c++ do-while

我试图添加向量的元素,条件是元素的总和大于(>)某个数字。这必须按顺序进行,所以最后我得到满足上述条件的几个“合并”元素

例如,如果MINSUM = 10且v_1 = 4,v_2 = 7,则v_1 + v_2 = 11> 10,退出循环 - 如果没有,则再添加v_3并再次检查条件。这就是我在做什么,但效果不好

vector < float >values_;        //this vector holds the real number I want to add
float sum_ = 0;
     ////////loop inside the vector 
for (unsigned t = 0; t < values_.size(); t++) {
        //        //////first , take the first element of the vector
        float cont_ = values_[t];
        //             /////and add the next value
        float cont_next = values_[t + 1];
        /////some stupid boolean
        bool check_point = false;
        sum_two_bins = cont_;
        //         ////////and now loop        
        do {
                sum_ += cont_next;
                t++;
                check_point = true;
                break;
        }
        while (sum_ < MINENTRIES);
        if (check_point)
                cout << " at the end, is the sum ok more than MINENTRIES? "
                    << sum_ << "  " << t << endl;
}

2 个答案:

答案 0 :(得分:2)

std::vector<float> values;
float sum = 0.0f;
for(const auto& value : values)
{
    if(sum += value > MINENTRIES)
          break;
}

cout << " at the end, is the sum ok more than MINENTRIES? " << sum << "  " << t << endl;

C ++ 98

std::vector<float> values;
float sum = 0.0f;
for(std::vector<float>::iterator it = values.begin(); it != values.end(); ++it)
{
    if(sum += *it > MINENTRIES)
          break;
}

cout << " at the end, is the sum ok more than MINENTRIES? " << sum << "  " << t << endl;

答案 1 :(得分:0)

有一个STL算法可以执行此任务:std::accumulate标题内的<numeric>

std::accumulate(v.begin(), v.end(), 0);