パープルハット

※当サイトではGoogleアドセンス広告を利用しています

C++ 2つのvectorが一致するか





作成した関数

//2つのvectorが一致するかどうか判定
template<class T>
 bool IsOverlapVector(const std::vector<T>& a, const std::vector<T>& b) {

     //サイズが不一致ならfalseを返す
     if (a.size() != b.size()) {
         return false;
     }

     //i番目の要素の一致を調べ、1回でも不一致があるならfalse
     for (int i = 0; i < a.size(); i++) {
         if (a[i] != b[i]) {
             return false;
         }
     }

    return true;
}





使用例

ソースコード

int main(){
    //選択肢
    std::vector<int> a = { 1, 3, 5 };
    std::vector<int> b = { 2, 4, 6 };
    std::vector<int> c = { 1, 3};
    std::vector<int> d = { 1, 3, 5 };

    //aとbの一致を確認
    std::cout << "a = bは" << IsOverlapVector(a, b) << std::endl;

    //aとcの一致を確認
    std::cout << "a = cは" << IsOverlapVector(a, c) << std::endl;
    
    //aとdの一致を確認
    std::cout << "a = dは" << IsOverlapVector(a, d) << std::endl;
}



実行結果

a = bは0
a = cは0
a = dは1