Which of the following is better and why? (In particular, C ++)
a.
int i(0), iMax(vec.length());//vec is a container, say std::vector for(;i < iMax; ++i) { //loop body }
b.
for( int i(0);i < vec.length(); ++i) { //loop body }
I saw advice for (a) because of the length call function. It bothers me. Doesn't any modern compiler make optimization (b) look like (a)?
Example (b) has a different meaning, for example, (a), and the compiler should interpret it when you write it.
If (for some reason I can't think of), I wrote the code for this:
for( int i(0);i < vec.length(); ++i) { if(i%4 == 0) vec.push_back(Widget()); }
I would not want the compiler to optimize every call to vec.length (), because I get different results.
I like:
for (int i = 0, e = vec.length(); i != e; ++i)
Of course, this will also work for iterators:
for (vector<int>::const_iterator i = v.begin(), e = v.end(); i != e; ++i)
, ( end() ), ( vector<int>::const_iterator ).
end()
vector<int>::const_iterator
, :
99,99% .
- , size() , , . , stick , , size() .
size()
:
, . for.
for
: - , :
for( vector<...>::size_type i = 0; i < v.size(); ++i ) { // vector size may grow. if( ... ) v.push_back( i ); // contrived, but possible } // note: this code may be replaced by a std::for_each construct, the previous can't. for( vector<...>::size_type i = 0, elements = v.size(); i != elements; ++i ) { }
? , . , .
colud be
for (vector<T>::iterator it=vec.begin();it!=vec.end();it++){ //loop body }
, .
. ( comp.lang.++. ).
,
int i = 0;
, , . , .
. .
- size_t.
, ++ std::vector<>::size_type.
std::vector<>::size_type
, C/++ .
( MSVS 2008 ).
.
int i(0), iMax(vec.size());//vec is a container, say std::vector for(;i < iMax; ++i) { //loop body }
for 2 .
for( int i(0);i < vec.size(); ++i) { //loop body }
for 8 . vec.size() .
for (std::vector<int>::const_iterator i = vec.begin(), e = vec.end(); i != e; ++i) { //loop body }
for 15 ( , )
, , a). b) c).
'it', . ,
for (int i=0;i<vec.size();++i){ //loop body }
vec.
: vec ?
vec
JRH
vec.length() , , (, , !). i "b", length "" !
vec.length()
i
length
typedef vector<int> container; // not really required, // you could just use vector<int> in for loop for (container::const_iterator i = v.begin(); i != v.end(); ++i) { // do something with (*i) }
v.end()
(b) / .
- ----
: GCC , . , , .
--- -
gcc:
https://www.in.redhat.com/software/gnupro/technical/gnupro_gcc.php3
Why not get around the problem completely with BOOST_FOREACH
#include <boost/foreach.hpp> std::vector<double> vec; //... BOOST_FOREACH( double &d, vec) { std::cout << d; }