James Dickens James Dickens - 1 month ago 6
C++ Question

De-Referencing each element of an std::vector of pointers to objects

Supposing that I have a class called

TextEntry
with some instance variables and a method
ask()
(which returns an integer).

I then create a vector of type:
std::vector<TextEntry*> d_text
(a vector of pointers of type
TextEntry
). I wish to iterate over all the elements in this vector and call the method
ask()
applied to each element. Is this the correct way to do it?

for (std::vector<TextEntry*>::iterator it = d_text.begin(); it != d_text.end(); ++it) {

TextEntry* TextEntryPointer = *it; // first dereference the iterator

TextEntry TextEntry = *TextEntryPointer; // dereference the TextEntry pointer

int j = TextEntry.ask();

}


For whatever reason this implementation is giving me an error so it would be helpful to know if the reason why is because of the above code or some other problem in the rest of my project.

Answer

I wish to iterate over all the elements in this vector and call the method ask() applied to each element. Is this the correct way to do it?

Almost.

Your program doesn't call ask on any element pointed by d_text but on a copy of each pointed element.


Is there a way to call it on the original element I am confused why it is a copy.

Yes. Instead of copy-constructing a TextEntry variable, you could use a reference variable instead:

TextEntry& TextEntry = *TextEntryPointer;

This refers to the object pointed by the element in the vector.

Or more simply, don't create an intermediate variable at all:

int j = TextEntryPointer->ask();

Perhaps not even for the pointer:

int j = (*it)->ask();

You could simplify the loop as well:

for(TextEntry* ptr : d_text) {
    int j = ptr->ask();
}

For whatever reason this implementation is giving me an error

There is a missing semicolon

TextEntry TextEntry = *TextEntryPointer // dereference the TextEntry pointer

PS. Avoid naming a variable with a same identifier as a type.