2016-04-26 16 views
1

私は以下で定義されるような文字列のベクトルを持っているとしましょう。別のベクトルを使ってベクトルの特定の要素を反復する

std::vector<int> indices; 
indices.push_back(0); 
indices.push_back(5); 
indices.push_back(6); 

どのように私は、例えば、アクセスのために、ベクトルindicesの要素によるベクターnamesに繰り返すことができます。

std::vector<std::string> names; 
names.push_back("Zero" ); 
names.push_back("One" ); 
names.push_back("Two" ); 
names.push_back("Three"); 
names.push_back("Four" ); 
names.push_back("Five" ); 
names.push_back("Six" ); 
names.push_back("Seven"); 
names.push_back("Eight"); 
names.push_back("Nine" ); 

また、のは、私はをループに要素を定義するベクトルを持っているとしましょう名前:"Zero","Five"、および"Six"?パターンを見つけるために何パターンか困難を持っていない要素を反復処理について、我々はパターンを見つけることができているすべての要素または要素の上に

for(vector<string>::iterator it=names.begin() ; it < names.end(); it++) 

反復処理、例えば、他のすべての要素、などしかし、どのように私はそれを知っていますか?別のベクトルの反復にどのようにベクトルを使用できますか?以下のような何か:

for(vector<int>::iterator it=indices.begin() ; it < indices.end(); it++) 
{ 
    names.at(indices.at(it)) 
    ... 
} 

答えて

1

あなたはまた、さらになインデックスにアクセスするためのラムダとstd::for_eachコール(バージョン1) を使用することができ、あなたがrvaluesとのforループ範囲ベースを使用することができます(バージョン2)

#include <vector> 
#include <algorithm> 

int main() 
{ 
    std::vector<std::string> names; 
    names.push_back("Zero"); 
    names.push_back("One"); 
    names.push_back("Two"); 
    names.push_back("Three"); 
    names.push_back("Four"); 
    names.push_back("Five"); 
    names.push_back("Six"); 
    names.push_back("Seven"); 
    names.push_back("Eight"); 
    names.push_back("Nine"); 

    std::vector<int> indices; 
    indices.push_back(0); 
    indices.push_back(5); 
    indices.push_back(6); 

    // version 1 
    std::for_each(std::cbegin(indices), std::cend(indices), 
    [&](auto &idx) { std::cout << names.at(idx) << "\n";}); 

    // version 2 
    for (auto &&idx : indices) 
    std::cout << names.at(idx) << "\n"; 

    return 0; 
} 
+0

どうやら、 'オート'C + 11'では問題があります。コンパイラは 'C++ 11での自動変更の意味について不平を言っています。それを取り除いてください。 – AFP

+0

これは 'C++ 14'に特有のものです。 'C++ 11 'を使用している場合は、' auto'を特定の型に置き換える必要があります。 – foo

2

それはこのように簡単です:注

for(vector<int>::iterator it=indices.begin() ; it != indices.end(); ++it) 
{ 
    names.at(*it); 
    names[*it]; // for faster but unvalidated access 
    ... 
} 

++itがより速くなる可能性があります(ただし遅くなることができない)ので、それはpostfixのであれば、あなたが気にしないとき、それは通常使用されていますまたはプレフィックス形式。 it != container.end()も一般的です(ランダムアクセスイテレータでは動作しませんが、たとえば、フォワードイテレータでは動作しません)ので、通常は使用されます。

3

あなたの提案はほぼ正しいです。 insdices.at(it)の代わりに、イテレータを逆参照する必要があります。しかし、あなたは、単にこのようにそれを行うことができます。

for(int index : indices) { 
    names[index]; 
} 

それとも、すべてのiのためにそのnames.size()>indices[i]を証明できない場合は、​​を使用することができます。

関連する問題