我正在嘗試對向量的值求和,但我對此有疑問。
向量的大小是 20 個元素,我試圖從當前位置計算 5 個元素的總和。
類似于:將元素從 1 到 5、2 到 6、3 到 7 等相加。
我認為我可以做一個 for 嵌套回圈,如下所示:
for (int a = 0; a < numVec.size(); a ) {
for (int b = a; b < numVec.size(); b )
{
if (aux < 5) {
cout << "B: " << b << endl;
sum = numVec[b].num;
}
if (aux > 4) {
aux = 0;
sumAux= sum;
sum= 0;
break;
}
aux ;
}
cout << "Sum: " << sumAux<< endl;
}
但是當我獲得第 15 名時遇到了一些問題,一切都出錯了,我不知道為什么。

如果你能幫助我,我非常感謝你。
uj5u.com熱心網友回復:
一種選擇是使內回圈范圍從 0-5
for (int a = 0; a < numVec.size(); a ) {
int sum = 0;
for (int b = 0; b < 5 && a b < numVec.size(); b ) {
sum = numVec[a b];
}
std::cout << sum << "\n";
}
另一種選擇是使用 std::accumulate
for (auto a = numVec.begin(); a < numVec.end(); a ) {
std::cout << std::accumulate(a, std::min(a 5, numVec.end()), 0) << '\n';
}
此外,@Bathsheba 在評論中提到的是保持運行總數,即 O(n)。
int sum = 0;
for (int a = 0; a < 5 && a < numVec.size(); a ) sum = numVec[a];
std::cout << sum << '\n';
for (int a = 5; a < numVec.size(); a ) {
sum = sum - numVec[a - 5] numVec[a];
std::cout << sum << '\n';
}
uj5u.com熱心網友回復:
整體aux和sumAux處理使您的邏輯比它需要的更復雜。
嘗試更像這樣的事情:
#include <algorithm>
const size_t size = numVec.size();
const size_t increment = 5;
for (size_t a = 0; a < size; a)
{
size_t stop = a std::min(size-a, increment);
sum = 0;
for (size_t b = a; b < stop; b)
sum = numVec[b].num;
cout << "Sum: " << sum << endl;
}
在線演示
或者:
#include <algorithm>
#include <numeric>
auto end = numVec.end();
decltype(numVec)::difference_type increment = 5;
for (auto start = numVec.begin(); start != end; start)
{
auto stop = start std::min(end-start, increment);
sum = std::accumulate(start, stop, 0,
[](auto a, const auto &elem){ return a elem.num; }
);
cout << "Sum: " << sum << endl;
}
在線演示
uj5u.com熱心網友回復:
如果您在開始撰寫代碼之前考慮更長的時間,它將對您有很大幫助。也許你可以拿一張紙寫下一些東西。
然后,如果您選擇長且會說話的變數名稱,它將對您有很大幫助。
所以,讓我們做一個圖片。我們在存盤它們的向量中寫入一些測驗值及其索引。請記住。在 C 中索引從 0 開始。
Value: 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
Index: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
所以,如果我們現在想要為每個 5 個值構建總和,那么我們需要添加
Index 0 1 2 3 4 Value: 21 22 23 24 25
Index 1 2 3 4 5 Value: 22 23 24 25 26
Index 2 3 4 5 6 Value: 23 24 25 26 27
. . .
Index 14 15 16 17 18 Value: 35 36 37 38 39
Index 15 16 17 18 19 Value: 36 37 38 39 40
所以,你可以看到。我們有一個總是遞增 1 的起始索引。從這個起始索引開始,我們總是將 5 個值相加。但是我們必須結束這個程序,正如你在上面看到的索引 15,所以 20 - 5。所以,總是,整個陣列的大小 - 子陣列的大小。
所以,讓我們先解決這個問題,我們可以大步前進:
#include <iostream>
#include <vector>
int main() {
// Our test data to play with
std::vector<int> data = { 21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40 };
// This is the size of the subarray. So the number of values that we want to sum up
int sizeOfSubarray = 5;
// And because we have a subarray size, the last summation starts at this index
int lastIndex = data.size() - sizeOfSubarray;
// So, now iterate over all data that needs to be summed up
for (int startIndex = 0; startIndex <= lastIndex; startIndex) {
// Because we have a new start index now, we start also with a 0 sum
int sum = 0;
// Calculate the end index of the sub array
int endIndexOfSubarray = startIndex sizeOfSubarray;
for (int sumIndex = startIndex; sumIndex < endIndexOfSubarray; sumIndex) {
// Some debug output
std::cout << "Startindex: " << startIndex << "\tSumindex: " << sumIndex << "\tValue: " << data[sumIndex] << '\n';
// Calculate the subarray sum
sum = sum data[sumIndex];
}
// Show the subarray sum
std::cout << "Sum: " << sum << '\n';
}
}
好,懂了。如果我們還想將陣列的值的末尾相加怎么辦?那么,如果 startindex 將遍歷整個陣列呢?讓我們看看這個。
Index 16 17 18 19 ? Value: 37 38 39 40 ?
Index 17 18 19 ? ? Value: 38 39 40 ? ?
Index 18 19 ? ? ? Value: 39 40 ? ? ?
Index 19 ? ? ? ? Value: 40 ? ? ? ?
你可以看到,起始索引一直運行到 < 20。所以 < 向量的大小。
如果求和的結束索引 > 19,那么 >= 向量的大小,我們可以將其限制為 19,
我們可以計算或使用簡單的 if 陳述句。
然后代碼看起來像這樣
#include <iostream>
#include <vector>
int main() {
// Our test data to play with
std::vector<int> data = { 21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40 };
// This is the size of the subarray. So the number of values that we want to sum up
int sizeOfSubarray = 5;
// So, now iterate over all data that needs to be summed up
for (int startIndex = 0; startIndex < data.size(); startIndex) {
// Because we have a new start index now, we start also with a 0 sum
int sum = 0;
// Calculate the end index of the sub array
int endIndexOfSubarray = startIndex sizeOfSubarray;
// If this index is too big ( > 20) then limit it to 20
if (endIndexOfSubarray > data.size()) {
endIndexOfSubarray = data.size();
}
// Claculate sum of sub array
for (int sumIndex = startIndex; sumIndex < endIndexOfSubarray; sumIndex) {
// Some debug output
std::cout << "Startindex: " << startIndex << "\tSumindex: " << sumIndex << "\tValue: " << data[sumIndex] << '\n';
// Calculate the subarray sum
sum = sum data[sumIndex];
}
// Show the subarray sum
std::cout << "Sum: " << sum << '\n';
}
}
我希望這個解釋有幫助
uj5u.com熱心網友回復:
這被認為是滾動總和等。您可以撰寫一個模板來操作指定視窗的向量上的二元函式:
#include <iostream>
# include <numeric>
# include <vector>
# include <functional>
using namespace std;
template<class T>
vector<T> roll_fun(vector<T> vec, int window,function<T(T, T)> func, T init){
int final_size = vec.size() - window 1;
vector<T> result(final_size);
for (int k = 0; k < final_size; k )
result[k] = accumulate(vec.begin() k, vec.begin() k window, init, func);
return result;
}
int main()
{ vector<double> myvec{1,2,2.3,3,4,5,6,7,8,9,1,2,3,4,5,6,7};
// rolling sum
vector<double> v = roll_fun<double>(myvec, 5, plus<double>(), 0);
for(auto i: v) cout<<i<<' ';
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/388758.html
標籤:C
