找出std::vector中所有元素的和的好方法是什么?
假设我有一个向量std::vector<int> vector,其中有几个元素。现在我要求所有元素的和。同样的东西有什么不同的表达方式?
找出std::vector中所有元素的和的好方法是什么?
假设我有一个向量std::vector<int> vector,其中有几个元素。现在我要求所有元素的和。同样的东西有什么不同的表达方式?
当前回答
prason已经提供了许多不同的(而且很好的)方法来做到这一点,这里没有一个需要重复。不过,我想建议另一种提高速度的方法。
如果你要经常这样做,你可能想要考虑“子类化”你的vector,这样元素的和就被分开维护(实际上不是子类化vector,因为缺少虚析构函数而存在问题——我说的更多的是一个包含和和和的类,has-a而不是is-a,并提供类似vector的方法)。
对于空向量,和设为零。每次插入向量时,将插入的元素加到和中。在每次删除时,减去它。基本上,任何可能改变底层向量的东西都会被拦截,以确保总和保持一致。
这样,您就有了一个非常有效的O(1)方法来“计算”任何时间点的和(只返回当前计算的和)。插入和删除将花费稍长的时间来调整总数,您应该考虑到这种性能影响。
如果向量的和比向量的改变更频繁,那么这些向量可能会从这个方案中受益,因为计算和的成本会在所有访问中摊销。显然,如果你只需要每小时求和,而向量每秒变化3000次,这是不合适的。
这样就足够了:
class UberVector:
private Vector<int> vec
private int sum
public UberVector():
vec = new Vector<int>()
sum = 0
public getSum():
return sum
public add (int val):
rc = vec.add (val)
if rc == OK:
sum = sum + val
return rc
public delindex (int idx):
val = 0
if idx >= 0 and idx < vec.size:
val = vec[idx]
rc = vec.delindex (idx)
if rc == OK:
sum = sum - val
return rc
显然,这是伪代码,您可能希望有更多的功能,但它显示了基本概念。
其他回答
实际上有相当多的方法。
int sum_of_elems = 0;
c++ 03
Classic for loop: for(std::vector<int>::iterator it = vector.begin(); it != vector.end(); ++it) sum_of_elems += *it; Using a standard algorithm: #include <numeric> sum_of_elems = std::accumulate(vector.begin(), vector.end(), 0); Important Note: The last argument's type is used not just for the initial value, but for the type of the result as well. If you put an int there, it will accumulate ints even if the vector has float. If you are summing floating-point numbers, change 0 to 0.0 or 0.0f (thanks to nneonneo). See also the C++11 solution below.
c++ 11及以上版本
b.即使将来发生变化,也会自动跟踪vector类型: # include <数字> Sum_of_elems = std::accumulate(vector.begin(), vector.end(), decltype(向量)::value_type (0)); 利用std:: for_each: std:: for_each (vector.begin (), vector.end (), [&] (int n) { Sum_of_elems += n; }); 使用基于范围的for循环(感谢Roger Pate): For (auto& n: vector) Sum_of_elems += n;
c++ 17及以上版本
使用std::reduce,它也照顾到结果类型,例如,如果你有std::vector<int>,你得到int作为结果。如果你有std::vector<float>,你得到float。或者如果你有std::vector<std::string>,你得到std::string(所有字符串连接)。很有趣,不是吗? 自动结果= std::reduce(v.begin(), v.end()); 这个函数还有其他重载,你甚至可以并行运行,如果你有一个大的集合,你想快速得到结果。
我是一个Perl用户,我们有一个游戏是找到各种不同的方法来增加一个变量…这里没有什么不同。在c++中,有多少种方法可以求出一个向量元素的和,答案可能是无穷大……
我的观点是:
使用BOOST_FOREACH,摆脱丑陋的迭代器语法:
sum = 0;
BOOST_FOREACH(int & x, myvector){
sum += x;
}
在索引上迭代(非常容易阅读)。
int i, sum = 0;
for (i=0; i<myvector.size(); i++){
sum += myvector[i];
}
另一个是破坏性的,像访问堆栈一样访问vector:
while (!myvector.empty()){
sum+=myvector.back();
myvector.pop_back();
}
最简单的方法是使用std:accumulate of a vector<int> a:
#include <numeric>
cout << accumulate(A.begin(), A.end(), 0);
prason已经提供了许多不同的(而且很好的)方法来做到这一点,这里没有一个需要重复。不过,我想建议另一种提高速度的方法。
如果你要经常这样做,你可能想要考虑“子类化”你的vector,这样元素的和就被分开维护(实际上不是子类化vector,因为缺少虚析构函数而存在问题——我说的更多的是一个包含和和和的类,has-a而不是is-a,并提供类似vector的方法)。
对于空向量,和设为零。每次插入向量时,将插入的元素加到和中。在每次删除时,减去它。基本上,任何可能改变底层向量的东西都会被拦截,以确保总和保持一致。
这样,您就有了一个非常有效的O(1)方法来“计算”任何时间点的和(只返回当前计算的和)。插入和删除将花费稍长的时间来调整总数,您应该考虑到这种性能影响。
如果向量的和比向量的改变更频繁,那么这些向量可能会从这个方案中受益,因为计算和的成本会在所有访问中摊销。显然,如果你只需要每小时求和,而向量每秒变化3000次,这是不合适的。
这样就足够了:
class UberVector:
private Vector<int> vec
private int sum
public UberVector():
vec = new Vector<int>()
sum = 0
public getSum():
return sum
public add (int val):
rc = vec.add (val)
if rc == OK:
sum = sum + val
return rc
public delindex (int idx):
val = 0
if idx >= 0 and idx < vec.size:
val = vec[idx]
rc = vec.delindex (idx)
if rc == OK:
sum = sum - val
return rc
显然,这是伪代码,您可能希望有更多的功能,但它显示了基本概念。
c++ 0 x只:
vector<int> v; // and fill with data
int sum {}; // or = 0 ... :)
for (int n : v) sum += n;
这类似于其他地方提到的BOOST_FOREACH,与与accumulate或for_each一起使用的有状态函子相比,在更复杂的情况下具有同样的清晰性。