我想知道我在c ++中两组之间的做法(B - A)

时间:2018-03-23 16:44:59

标签: c++

我不能在两组之间做(B-A)并且我做我的代码并且它可以找到这个过程但是当set 1的大小等于set 2的大小但是如果两个大小是diffrance这个输出是-----> {} 这是我的代码

int sizeofarray1 ,sizeofarray2 ; 
cout << "Enter your size of array one :";
cin >> sizeofarray1;
cout << "Enter your size of array two :";
cin >> sizeofarray2;
int arr1[sizeofarr1], arr2[sizeofarr2], ;
for (int i = 0 ; i < sizeofarray1 ; i++)
    {
        cin >> arr1[i];                                                  // Cartesian product of A and B  ( B - A) 
    }

    for (int i = 0 ; i < sizeofarray2 ; i++)
    {
        cin >> arr2[i];
    }
    cout << "\n{ " ;
  for ( int k = 0 ; k < sizeofarray1; k++)       
   {

        {
            for (int i = 0 ; i < sizeofarray2;)
            {
                if   (arr2[i] == arr1[k] ) 
                {
                    break;  
                }
                if ( i < k  )       // if to i++ before print result
                    {
                        i++;
                    }
                else if (arr2[i] != arr1[k] )
                {
                    cout << arr2[k] << " ";
                    break;  
                }

            }

        }
    }
    cout << "}";

1 个答案:

答案 0 :(得分:1)

您可以使用std::set_differencehttp://en.cppreference.com/w/cpp/algorithm/set_difference

#include <iostream>
#include <algorithm>
#include <vector>
#include <iterator>

int main() {
    std::vector<int> v1 {1, 2, 5, 5, 5, 9};
    std::vector<int> v2 {2, 5, 7};
    std::vector<int> diff;

    std::set_difference(v1.begin(), v1.end(), v2.begin(), v2.end(), 
                        std::inserter(diff, diff.begin()));

    for (auto i : v1) std::cout << i << ' ';
    std::cout << "minus ";
    for (auto i : v2) std::cout << i << ' ';
    std::cout << "is: ";

    for (auto i : diff) std::cout << i << ' ';
    std::cout << '\n';
}