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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With