I have this code
void split(v开发者_运维问答ector<float> &fvec, string str)
{
int place = 0;
for(int i=0; i<str.length(); i++)
{
if(str.at(i) == ' ')
{
fvec.push_back(atoi(str.substr(place,i-place).c_str()));
place=i+1;
}
}
fvec.push_back(atoi(str.substr(place).c_str()));
}
What im trying to do is pass a reference to a vector into the method so it splits the string i give it into floats without copying the vector... i dont want to copy the vector because it will be containing 1000's of numbers.
is it not possible to pass a vector by reference or am i just making a stupid mistake?
if it helps heres the code im testing it out with
int main (void)
{
vector<float> fvec;
string str = "1 2 2 3.5 1.1";
split(&fvec, str);
cout<<fvec[0];
return 0;
}
It is indeed possible. You're just using the wrong syntax. The correct way to do it is :
split(fvec, str);
What you're doing is wrong because it passes the address of the vector as the intended reference.
If you are using a modern compiler, like gcc/g++, it does named return value optimization for you, so that you don't need to pass the return value by reference or pointer.
See:
http://en.wikipedia.org/wiki/Return_value_optimization/
http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/
You are passing the address of the vector. (split(&fvec, str);
)
The call should be split(fvec, str);
without the &
.
The obvious thing that leaps out is the split(&fvec, str);
in your main
function, which means you're not passing a vector but the address of a vector. This is the right thing to do if your vector parameter is a pointer, but not if it's a reference. Use split(fvec, str);
instead.
Also, one thing you might consider is building the vector in the function and returning it as normal. This is likely to be optimized out by the compiler. If you're not using a compiler with return value optimization ability, you're likely to get better results by changing compilers than trying to tune your code manually.
And, if you're worried about passing big data structures around, what of the string parameter? Doesn't that get large?
精彩评论