Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a pointer to Object from std::vector<Object> in range-based for loop

I have a vector of objects - journal:

    std::vector<Object> journal;
    std::vector<Object*> filteredJournal;
    for (const auto &element : journal) {
            if (element.data[1] == user) {
                filteredJournal.push_back(&element);
            }
    }

I want to fill the vector of pointers to these objects, filteredJournal, with pointers to specific objects from journal. I tried to use & on element, but of course it gives me an error that I'm giving a wrong argument for push_back() function. What's is the right way to do that?

like image 303
kekyc Avatar asked Feb 27 '26 01:02

kekyc


1 Answers

The problem is here:

const auto &element : journal

You bind a const reference to each element. So when you use it to take an address, you get a pointer to a const element. And you can't pass it to a function that expects a pointer to an object that is not const-qualified.

Just remove the const qualifier:

auto &element : journal

The usual caveats about iterator, reference and pointer invalidation apply of course. Make sure the filteredJournal doesn't last longer than the time span in which its pointers are guaranteed to be pointing at valid objects.

like image 179
StoryTeller - Unslander Monica Avatar answered Mar 01 '26 14:03

StoryTeller - Unslander Monica



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!