Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

referencing a vector

I have this code

void split(vector<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;
}
like image 937
CurtisJC Avatar asked Sep 05 '26 16:09

CurtisJC


1 Answers

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.

like image 99
fouronnes Avatar answered Sep 07 '26 09:09

fouronnes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!