Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to pass the first element of an object to a function in C++?

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;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading