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.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.