2012-06-23 18 views

risposta

8

C++ 11, che si sta utilizzando, se questo viene compilato, consente le seguenti:

for (string& feature : features) { 
    // do something with `feature` 
} 

This is the range-based for loop.

Se non si desidera mutare la funzione, è può anche dichiararlo come string const& (o solo string, ma ciò causerà una copia non necessaria).

22

Prova questo:

for(vector<string>::const_iterator i = features.begin(); i != features.end(); ++i) { 
    // process i 
    cout << *i << " "; // this will print all the contents of *features* 
} 

Se si utilizza C++ 11, allora questo è troppo legale:

for(auto i : features) { 
    // process i 
    cout << i << " "; // this will print all the contents of *features* 
} 
+0

Forse si intende '++ i' e non' i ++ '. –

+0

In realtà è la stessa cosa. –

+7

[No, non lo è!] (Http://stackoverflow.com/questions/24901/is-there-a-performance-difference-between-i-and-i-i-c) e dovresti usare un 'const_iterator' non è solo un' iteratore'. Questo è il codice della piastra della caldaia, dovresti impararlo bene e abbastanza bene da farlo bene anche se richiesto quando dormi. –

Problemi correlati