在C++中使用do-while循环对向量的元素求和
Summing a vector's elements with do-while loop in C++
我试图在元素之和大于(>)某个数字的条件下添加向量的元素。这必须按顺序进行,所以最后我得到了几个满足上述条件的"合并"元素
例如,如果MINSUM=10和v_1=4,v_2=7,那么v_1+v_2=1>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;
}
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;
有一个STL算法可以执行此任务:<numeric>
标头中的std::accumulate
。
std::accumulate(v.begin(), v.end(), 0);
相关文章:
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么
- 在 C++ 中输出枚举类类型的向量元素
- 用向量的向量元素初始化向量的空向量
- 为什么不允许使用可变长度数组作为向量元素?
- 在函数中传递向量元素
- 使用 Rcpp 加速替换迭代算法中的列表和向量元素是否合法?
- 返回向量元素的 l 值的正确方法是什么?
- 当向量增长时,指向向量元素的C++指针是否无效
- 如何在C++中从一个向量元素减去std::unorderede_map向量元素并更新它
- C++:向量元素赋值导致访问冲突
- 将向量元素与字符串元素进行比较,而不初始化向量
- 从2D矢量中找出最小尺寸的向量元素的更好方法
- 当我尝试将一个向量元素的值分配给另一个向量元素时,为什么我的应用程序会崩溃
- 使用递归C++向量元素的总和
- 如何查找为数组中的最低值编制索引的向量元素
- 限制指针访问STL ::向量元素
- 访问索引指向向量元素时的seg故障 - 做错了什么
- 如何使用指针访问向量元素的各个元素
- 向量元素数据损坏了Find()操作
- 将字符值分配给向量元素.C