2012-06-23 10 views
8

このC++ベクタをどのように反復処理しますか?使用しているC++文字列のベクトルをどのように反復するのですか?

vector<string> features = {"X1", "X2", "X3", "X4"};

+3

見つけることが1つの非常に簡単:あなたがC++ 11を使用している場合、これはあまりにも合法である

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

を。 –

答えて

8

C++ 11、これはコンパイルする場合、以下のことができます:

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

This is the range-based for loop.

この機能を変異させたくない場合は、 string const&(またはちょうどstringですが、不要なコピーが発生します)と宣言することもできます。

22

このお試しください:ええ、

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--i-in-c) 'iterator'だけではなく、' const_iterator'です。これはボイラープレートのコードです。眠ったときに尋ねられたとしても、それを正しく取得するには十分によく学ぶべきです。 –

関連する問題