How to get the difference of two arrays into a vector in C++

2 Answers

0 votes
#include <iostream> 
#include <algorithm>
#include <vector> 
  
using std::vector;
using std::cout;  
using std::endl;

#define SIZE 5
  
int main()
{
    int arr1[] = { 13, 1, 5, 2, 9 };
    int arr2[] = { 1, 10, 9, 17, 5 };
    vector<int> vec(SIZE * 2);         
  
    std::sort(arr1, arr1 + SIZE);     
    std::sort(arr2, arr2 + SIZE);   
  
    vector<int>::iterator it;
    it = std::set_difference(arr1, arr1 + SIZE, arr2, arr2 + SIZE, vec.begin());
  
    vec.resize(it - vec.begin());
  
    for (it = vec.begin(); it != vec.end(); it++) {
        cout << *it << ' ';
    }
}
 
 
  
/*
run:
  
2 13 
  
*/

 



answered Apr 25, 2018 by avibootz
edited Feb 5, 2025 by avibootz
0 votes
#include <iostream> 
#include <algorithm>
#include <vector> 
 
using std::vector;
using std::cout;  
using std::endl;
 
int main()
{
    int arr1[] = { 13, 1, 5, 2, 9 };
    int arr2[] = { 1, 10, 9, 17, 5 };
    vector<int> vec(10);         
 
    std::sort(arr1, std::end(arr1));     
    std::sort(arr2, std::end(arr2));     
 
    vector<int>::iterator it;

    it = std::set_difference(std::begin(arr1), std::end(arr1), 
                             std::begin(arr2), std::end(arr2), 
                             vec.begin());
 
    vec.resize(it - vec.begin());
 
    for (it = vec.begin(); it != vec.end(); it++) {
        cout << *it << ' ';
    }
}


 
/*
run:
 
2 13 
 
*/

 



answered Feb 5, 2025 by avibootz

Related questions

1 answer 124 views
1 answer 87 views
1 answer 102 views
1 answer 105 views
1 answer 100 views
...