2016-04-26 25 views
2

ループ選択の条件に基づいています。if条件に基づいてforループを選択する

if(valid) 
for (std::multimap<int,int>::reverse_iterator rit=id_count.rbegin(); mcount<10 && rit!=id_count.rend();++rit) 
else 
for (std::multimap<int,int>::iterator rit=id_match.begin(); mcount<10 && rit!=id_match.end();++rit) 

{ 
    //this is common for both for loop 
} 

これをC++でどのように実現するには?

+3

ループ本体の中で共通の機能を使用しますか? – Lundin

+0

C++ 14にアクセスできない場合は、 'std :: for_each'を使い、汎用ラムダを渡します。 – StoryTeller

+0

@StoryTeller:追加の終了条件を持つ 'std :: for_each'?それはおそらくかなり醜い/非効率になるでしょう – MikeMB

答えて

3

あなたは選択の余地はないが、非常に大まかにこのように、機能に共通部分を置く:

void somefunction(...) 
{ 
    //this is common for both for loops 
} 

if (valid) 
{ 
    for (std::multimap<int,int>::reverse_iterator rit=id_count.rbegin(); mcount<10 && rit!=id_count.rend();++rit) 
    somefunctiuon(...); 
} 
else 
{ 
    for (std::multimap<int,int>::iterator rit=id_match.begin(); mcount<10 && rit!=id_match.end();++rit) 
    somefunctiuon(...); 
} 
1

をこれは、ループロジックを組み合わせた価値ないだと間違いなく実例として最も有用です、それは動作しますが。 ...関心値のためにここに提供

#include <iostream> 
#include <map> 

int main() 
{ 
    std::multimap<int,int> id_count = { {1,2}, {9, -2}, {1,44}, {2,3}, {3,5}, {7,34} }; 

    for (int valid = 0; valid < 2; ++valid) 
    { 
     std::cout << "valid " << valid << '\n'; 
     int mcount = 0; 
     for (std::multimap<int,int>::iterator it = valid ? id_count.rbegin().base() 
                 : id_count.begin(); 
      mcount<10 && (valid ? it--!=id_count.begin() : it!=id_count.end()); 
      (valid ? it : ++it), ++mcount) 
     { 
      std::cout << "[mcount " << mcount << "] " 
       << it->first << ',' << it->second << '\n'; 
     } 
     std::cout << '\n'; 
    } 
} 
あなたはテンプレート関数を作成することができます
1

#include <map> 
#include <iostream> 

template<typename I> void func(I begin, I end) { 
    int mcount = 0; 
    for (I it = begin; mcount < 10 && it != end; ++it) { 
     ++mcount; 
     std::cout << "[mcount " << mcount << "] " 
      << it->first << ',' << it->second << '\n'; 
    } 
} 

int main() { 
    std::multimap<int,int> id_count = { {1,2}, {9, -2}, {1,44}, {2,3}, {3,5}, {7,34} }; 
    for (int valid = 0; valid < 2; ++valid) { 
     std::cout << "valid " << valid << '\n'; 
     if (valid) { 
      func(id_count.rbegin(), id_count.rend()); 
     } else { 
      func(id_count.begin(), id_count.end()); 
     } 
     std::cout << '\n'; 
    } 
} 

しかし、この解決策は少し複雑なので、ループ本体を置くように(他の方法を検討私見関数)。

0

のようにあなたは、 "有効なの#if" 試すことができます:あなたはまた、使用するオプションを持っているC++ 14では

#if 0 for(i=1;i<10;++i) #else for(i=2;i<9;++i) #endif { cout << i << endl; }

0

一般的なラムダ:

auto common_code = [/* Capture state if needed */] (auto& Iter) 
{ 
    // Your common code 
}; 

if (valid) 
    for (std::multimap<int, int>::reverse_iterator rit = id_count.rbegin(); mcount < 10 && rit != id_count.rend(); ++rit) 
     common_code(rit); 
else 
    for (std::multimap<int, int>::iterator rit = id_match.begin(); mcount < 10 && rit != id_match.end(); ++rit) 
     common_code(rit); 
関連する問題