2

私はvector<ClassA>(たとえばmy_vector、このClassA 自体が ClassB のベクトルであるif condition)を持っており、次のような条件をテストするために書きたい

(1)。1 つの要素だけが空ではなく、他のすべてが空である場合 (my_vector のサイズが 5 であるため、my_vector[0]、my_vector[1]、.. )

(2) また、要素の 2 つが空ではなく、他の要素が空である場合 (他のペアについても同様)

(3) 同様に、3 つ以上の要素が空でない

私はこれをどのようにコーディングするか考えています

これは私の試みです

if (!my_vector[0].empty() && my_vector[1].empty() && my_vector[2].empty() && .. &&  
         my_vector[4].empty()){ //process 1}
else if (!my_vector[1].empty() && my_vector[0].empty() && my_vector[2].empty() && ..){ 
         //process 2}
else if(!my_vector[2].empty() && my_vector[0].empty() && my_vector[1].empty() && ..){
        //process 3}
...
...

else if (!my_vector[0].empty() && !my_vector[1].empty() && my_vector[2].empty() && ..   
         my_vector[4].empty()){ //process n}
else if (!my_vector[0].empty() && !my_vector[2].empty() && my_vector[1].empty() && ..   
         my_vector[4].empty()){ //process n+1}
....
....
else if (!my_vector[0].empty() && !my_vector[1].empty() && !my_vector[2].empty() &&    
         my_vector[3].empty() && my_vector[4].empty()){ //process p}
....
like wise

これはテストするのが本当に難しい方法であり、これを行うための方法論的な方法です。 前もって感謝します。

4

4 に答える 4

6

とラムダのcount_ifテンプレート関数を使用する<algorithm>と、コンパクトで明確なソリューションが得られます。

unsigned int non_empties = std::count_if(myvector.begin(), myvector.end(), [](const ClassA & c) { 
     return !c.empty();
});

if (non_empties == 1) {
  // process 1
} else if (non_empties == 2) {
  // process 2
} else if (non_empties >= 3) {
  // process 3
}

ライブラリは、この<algorithm>ような非常に実用的なソリューションを提供する一方で、驚くほど無視されることがよくあります。

于 2013-06-06T15:31:28.100 に答える
1

空要素と空でない要素の組み合わせが問題にならない場合は、コレクションを反復処理して、空の要素の数を取得できます。

int size = my_vector.size();
int emptyCount = 0;
for (int i = 0; i < size; i++) {
    emptyCount += (my_vector[i].empty() ? 1 : 0);
}

if (emptyCount == 0) {
    // no elements are empty
} else if (emptyCount == 1) {
    // only one element is empty
} else if { emptyCount == 2) {
    // two elements are empty
} ...

最終的に、この方法では、条件ごとに if/else-if が必要になります。ただし、これはパーセンテージを使用するように拡張できます (コレクションがランダムなサイズになる場合)。

于 2013-06-06T15:26:48.510 に答える
0

パターンの配列 (概念的には の 2D 配列bool) を定義します。次に、各行を順番に繰り返し、一致する行を見つけます。次に、その行に対応する関連する関数を呼び出します (関数ポインターの配列が必要になる場合があります)。

于 2013-06-06T15:23:58.807 に答える
0

おそらく、新しい c++11 関数 all_of、none_of がここで役立ちます。

だからあなたはこのようなことをすることができます

auto iter_begin = my_vector.begin();
auto iter_end = my_vector.end();
auto is_empty = [](decltype(*iter_begin) const & param){ return param.empty();};
auto is_not_empty = [](decltype(*iter_begin) const & param){ return !param.empty();};

if(iter_begin->empty() && all_of(iter_begin + 1, iter_end, is_empty ))

else if(all_of(iter_begin, iter_begin + 1, is_not_empty) && all_of(iter_begin + 2, iter_end, is_empty))

else if(all_of(iter_begin, iter_begin + 2, is_not_empty) && all_of(iter_begin + 3, iter_end, is_empty))

等々

于 2013-06-06T15:27:50.767 に答える