I have seen code which use vector,
vector<int>s;
s.push_back(11);
s.push_back(22);
s.push_back(33);
s.push_back(55);
for (vector<int>::iterator it = s.begin(); it!=s.end(); it++) {
cout << *it << endl;
}
It is same as
for (auto it = s.begin(); it != s.end(); it++) {
cout << *it << endl;
}
How safe is in this case the use of the auto keyword? And what about if type of vector is float
? string
?
This is new item in the language which I think we are going to be struggling with for years to come. The 'auto' of the start presents not only readability problem , from now on when you encounter it you will have to spend considerable time trying to figure out wtf it is(just like the time that intern named all variables xyz :)), but you also will spend considerable time cleaning after easily excitable programmers , like the once who replied before me. Example from above , I can bet $1000 , will be written "for (auto it : s)", not "for (auto& it : s)", as a result invoking move semantics where you list expecting it, modifying your collection underneath .
Another example of the problem is your question itself. You clearly don't know much about stl iterators and you trying to overcome that gap through usage of the magic of 'auto', as a result you create the code that might be problematic later on
It's additional information, and isn't an answer.
In C++11 you can write:
for (auto& it : s) {
cout << it << endl;
}
instead of
for (auto it = s.begin(); it != s.end(); it++) { cout << *it << endl; }
It has the same meaning.
Update: See the @Alnitak's comment also.
If you want a code that is readable by all programmers (c++, java, and others) use the original old form instead of cryptographic new features
atp::ta::DataDrawArrayInfo* ddai;
for(size_t i = 0; i < m_dataDraw->m_dataDrawArrayInfoList.size(); i++) {
ddai = m_dataDraw->m_dataDrawArrayInfoList[i];
//...
}
The auto keyword gets the type from the expression on the right of =. Therefore it will work with any type, the only requirement is to initialize the auto variable when declaring it so that the compiler can deduce the type.
Examples:
auto a = 0.0f; // a is float
auto b = std::vector<int>(); // b is std::vector<int>()
MyType foo() { return MyType(); }
auto c = foo(); // c is MyType
auto
keyword is intended to use in such situation, it is absolutely safe. But unfortunately it available only in C++0x so you will have portability issues with it.
Source: Stackoverflow.com