C ++ for using a temporary loop variable

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)?

+5
source share
14 answers

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.

+12
source

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 ).

+10

, :

99,99% .

- , size() , , . , stick , , size() .

+5

:

, . 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 ) {
}
+3

? , . , .

colud be

for (vector<T>::iterator it=vec.begin();it!=vec.end();it++){
 //loop body
}
+2

, .

. ( comp.lang.++. ).

,

int i = 0;

, , . , .

+2

:

. .

- size_t.

, ++ std::vector<>::size_type.

, C/++ .

+2

( 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).

+1

, :

for (vector<T>::iterator it=vec.begin();it!=vec.end();it++){
 //loop body
}

'it', . ,

for (int i=0;i<vec.size();++i){
 //loop body
}

vec.

+1

: vec ?

.

JRH

0

vec.length() , , (, , !). i "b", length "" !

0

:

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() ,
0
0
source

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;
}
0
source

All Articles