假设我有一个由 n 个元素组成的数组。
1 2 3 4 5 6 ... n
我需要找到一种方法来使用 C++ 提取此数组中连续元素的总和。 像这样:
1, 2, 3,...n, 1+2, 2+3, 3+4,...(n-1)+n, 1+2+3, 2+3+4,...(n-2)+(n-1)+n,...1+2+3...n
到目前为止,我发现我需要通过在每次运行时对一定数量的元素求和来遍历这个数组。我不确定是否可以实现我上面解释的算法。可能有更好的解决方案,但这是我能想到的最好的解决方案。
最佳答案
您可以使用 std::transform
来执行此操作:
std::transform(
v.begin(), v.end()-1,
v.begin()+1,
std::ostream_iterator<int>(std::cout, "\n"),
std::plus<int>()
);
当然你不必在输出时使用 ostream_iterator,你也可以使用另一个容器迭代器,或者一个 std::back_inserter
用于容器或任何其他 OutputIterator
引用资料
http://en.cppreference.com/w/cpp/algorithm/transform
http://en.cppreference.com/w/cpp/utility/functional/plus
http://en.cppreference.com/w/cpp/container/vector
编辑:
std::vector<int> v(100), t;
//this just populates v with 1,2,3...100
std::iota(v.begin(), v.end(), 1);
std::transform(
v.begin(), v.end()-1, v.begin()+1,
std::back_inserter(t),
std::plus<int>()
);
std::transform(
t.begin(), t.end()-1, v.begin()+2,
std::ostream_iterator<int>(std::cout, "\n"),
std::plus<int>()
);
关于c++ - 数组中连续元素的总和,C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13108622/