void GenerateNativeGamma(vector<float>& gammaNative,
float dDetX,
float sdd,
float moduleGapX,
int nModule,
int nChanDetX)
{
float L = 7*dDetX + (0.78/2+0.11/2);
gammaNative.push_back(0);
for (float n = 6.5; n>=-6.5; n--)
{
gammaNative.push_back( atanf(L/sdd)-atanf(n*dDetX/sdd));
}
gammaNative.push_back(2*atanf(L/sdd));
if( !gammaNative.empty())
{
float lastBonM = gammaNative.back(); // ERROR HAPPENS HERE!!!
gammaNative.push_back( lastBonM +2*atanf(moduleGapX/2/sdd) );
}
......
}
int main()
{
vector<float> gammaNative;
GenerateNativeGamma( gammaNative, 1.02, 869.5, 2.087,47, 24);
}
I am passing a vector by reference into a function from main()
; The purpose is to modify the vector inside it.
Then I have this " offset out of range " error when trying to get the last element via vector.back()
like following picture showing:
The vector is not empty, so it should have a back()
. Then I have no idea what the problem is here? Or this is not the right way to do it, then how should I modify a vector (dynamic) inside another function? Thanks a lot.
Note that resizing a vector may cause the underlying array to be moved, thus invalidating all pointers, references and iterators to it. When you push_back onto the vector you've passed via reference it can be resized and, of course, the reference will become invalid.
A quick fix would be to use reserve on the vector before calling the function, making sure enough elements can be pushed onto it without reallocation.
A better solution would probably be to return a copy.
EDIT: a quick example
vector<float> vec;
vec.reserve(50);
funcThatAdds50Floats(vec);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.