Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

What are the pros/cons to using the auto keyword, especially in for loops? for(s

ID: 652713 • Letter: W

Question

What are the pros/cons to using the auto keyword, especially in for loops?

for(std::vector<T>::iterator it = x.begin(); it != x.end(); i++)
{
   it->something();
}

for(std::map<T>::iterator it = x.begin(); it != x.end(); i++)
{
   it->second->something();
}

for(auto it = x.begin(); it != x.end(); i++)
{
   it->??
}
Seems like if you don't know whether you have an iterator for a map or a vector you wouldn't know whether to use first or second or just directly access properties of the object, no?

This reminds me of the C# debate on whether to use the keyword var. The impression I'm getting so far is that in the C++ world people are ready to adopt the auto keyword with less of a fight than var in the C# world. For me my first instinct is that I like to know the type of the variable so I can know what operations I can expect to perform on it.

Explanation / Answer

In your example:

for(auto it = x.begin(); it != x.end(); i++)
{
it->??
}
there has to be a declaration for x visible. Therefore the type of it should be obvious. If the type of x isn't obvious, then the method is too long, or the class is too large.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote