2012-06-23 25 views

Antwort

8

C++ 11, die Sie verwenden, wenn diese kompiliert, kann der folgende:

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

This is the range-based for loop.

Wenn Sie möchten, dass das Feature nicht mutieren, Sie kann es auch als string const& (oder nur string, aber das wird eine unnötige Kopie verursachen).

22

Try this:

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

Wenn Sie C++ 11 verwenden, dann ist dies legal zu:

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

Vielleicht meinen Sie "++ i" und nicht "i ++". –

+0

Eigentlich ist es das Gleiche. –

+7

[Nein, ist es nicht!] (Http://stackoverflow.com/questions/24901/is-there-a-performance-difference-between-i-and-i-in-c) und Sie sollten eine verwenden 'const_iterator' ist nicht nur ein' iterator'. Dies ist ein Kesselblech-Code. Sie sollten es gut und gut genug lernen, um es richtig zu machen, auch wenn Sie im Schlaf gefragt werden. –

Verwandte Themen