我有这个问题:
int nCab = 11;
int nCabCombo;
std::vector<int>counter(nCab);
for(int i = nCab; i > 0; i--)
{
counter[i] = i-1;
std::cout<<counter[i]<<std::endl;
}
nCabCombo = std::accumulate(counter.begin(),counter.end(),0);
std::cout<<nCabCombo<<std::endl;
nCabCombo的输出是45,当它应该是55时,由于某种原因,累加功能没有添加10在我的计数器向量的索引11处。有人能告诉我,我在做错了吗?谢谢!
答案 0 :(得分:1)
You do not have an index 11. You have 11 elements in you vector which means the valid indexes are [0, 10]
. counter[i] = i-1;
is undefined behavior since you are accessing one past the end of the vector.
Ignoring the UB your vector actually contains {0,0,1,2,3,4,5,6,7,8,9}
which is 45
Note: The reason it does not contain a -1
is the for loop runs for i > 0
so i
will never be 0
and we will never set the first element of the vector so it remains 0
from the construction of the vector.
答案 1 :(得分:1)
As others mentioned, you are accessing the element out of bounds.
However, instead of writing a loop and getting into this sort of trouble, you could use std::iota:
#include <vector>
#include <algorithm>
int main()
{
int nCab = 11;
std::vector<int>counter(nCab);
std::iota(counter.begin(), counter.end(), 0);
//...
}
If for some reason you really wanted to loop and populate the array in reverse (high index to low index), you could use std::generate and use the reverse iterators:
#include <vector>
#include <algorithm>
int main()
{
int nCab = 11;
std::vector<int>counter(nCab);
int i = 11;
std::generate(counter.rbegin(), counter.rend(), [&i] {return --i;});
//...
}
答案 2 :(得分:0)
counter[i] = i-1; //when i == 11, this is an off by one error
An array, and by extension a vector, has range from [0, size)
. If it has nCab
elements, the maximum index is only nCab - 1
. You're storing the last element outside the bounds of the vector. You should change it to:
counter[i - 1] = i-1;
The missing element would have been 10
. When accumulate
runs, that is why your sum is off by 10
.