2012-06-23 19 views

उत्तर

8

सी ++ 11 है, जो आप अगर यह संकलित उपयोग कर रहे हैं, तो निम्न की अनुमति देता है:

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

This is the range-based for loop.

आप इस सुविधा का उत्परिवर्तित नहीं करना चाहते हैं, तो आप इसे string const& (या केवल string के रूप में घोषित कर सकते हैं, लेकिन इससे एक अनावश्यक प्रतिलिपि होगी)।

22

इस प्रयास करें:

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

आप सी ++ 11 का उपयोग कर रहे हैं, तो इस कानूनी भी है:

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

शायद आपका मतलब है '++ i' और 'i ++' नहीं। –

+0

असल में यह वही बात है। –

+7

[नहीं, यह नहीं है!] (Http://stackoverflow.com/questions/24901/is-there-a-performance-difference-between-i-and-i-in-c) और आपको एक का उपयोग करना चाहिए 'const_iterator' सिर्फ एक 'इटरेटर' नहीं है। यह बॉयलर प्लेट कोड है, आपको इसे अच्छी तरह से सीखना चाहिए और सोते समय भी सही होने के लिए पर्याप्त है। –

संबंधित मुद्दे