Home > Back-end >  How to pass the first element of an object to a function in C ?
How to pass the first element of an object to a function in C ?

Time:11-20

I am trying to send the first element of an object to a function and modify its attributes and return back.

I have already created a Ray object with 20000 rays. Each single ray has its own properties. How can I pass the first ray to a function to modify one of its property since I dont want to pass all rays because of computation time.

I tried to create a function that recevies a ray;

std::vector<Ray> hi(std::vector<Ray> bb)
{
    bb.bounces  ;
    return bb;
}

and I tried to pass the first ray as:

hi(rays[0]);

but I receive 'no suitable used-defined conversion from "Ray" to "std::vector<Ray, std::allocator" exists.

Thank you for your help.

CodePudding user response:

If you want to pass a single Ray, simply do so. If you want to modify it, pass it as reference (non-const), optionally returing reference to original:

Ray &hi(Ray &bb)
{
    bb.bounces  ; // modify the original, passed as reference
    return bb; // return reference to original, for convenience
}

Or, if you don't want to modify original, but return a new, modified Ray, simply don't make it a reference:

Ray hi(Ray bb)
{
    bb.bounces  ; // argument is value, meaning copy, modify it
    return bb; // return the copy
}

Or, another way to do the same, by passing const reference:

Ray hi(const Ray &bb)
{
    auto result = bb; // get a copy
    result.bounces  ; // modify copy
    return result; // return copy
}

If you use this option (either of above 2), you then need to modify the original by assignment:

rays[0] = hi(rays[0]);
  • Related