How to compare 2 vectors and create a separate vec

2019-07-31 18:28发布

问题:

i'm looking at creating an algorithm that will compare 2 vectors (v1,v2), and create a new vector v3 that will hold the values not shared between v1 and v2.

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

using namespace std;

int main(int args[])
{
vector<int> v1 = { 1,2,3,4,5,6,7,8,9 };
vector<int> v2 = { 1,2,6 };
vector<int> v3; //V3 should equal = {3,4,5,7,8,9}.

return 0;
}

The vectors will always be sorted.

回答1:

If, as in your example, the ranges are sorted then you can use std::set_symmetric_difference. It will return all elements that are not shared between the two ranges. Using you example you would use

std::set_symmetric_difference(v1.begin(), v1.end(), v2.begin(), v2.end(), std::back_inserter(v3));

So putting it all together we have

int main()
{
    std::vector<int> v1 = { 1,2,3,4,5,6,7,8,9 };
    std::vector<int> v2 = { 1,2,6 };
    std::vector<int> v3; //V3 should equal = {3,4,5,7,8,9}.

    std::set_symmetric_difference(v1.begin(), v1.end(), v2.begin(), v2.end(), std::back_inserter(v3));

    for (auto e : v3)
        std::cout << e << " ";

    return 0;
}

Output:

3 4 5 7 8 9

Live example



回答2:

Sorry to trouble and add new answer here. NathanOliver has given precise answer. But for fun if I had to write my own function to implement this, I tried it on arrays instead of vector, (for changing code for vector will be trivial task).

Adding my code snippet here.

#include<iostream>

using namespace std;

int arr1[]={2,3,6,10};
int arr2[]={3,5,7,9,10};

int result[10];
int result_size=0;

void getUncommonValues(int *arr1, int size1, int *arr2, int size2){
    if ( (size1 == 0) && (size2 == 0) )
        return;

    if( size1 == 0){
        result_size=size2;
        for (int i=0; i < size2; i++)
            result[i] = arr2[i];
    }

    if (size2 == 0){
        result_size=size1;
        for (int i=0; i < size1; i++)
            result[i] = arr1[i];
    }

    int i1=0, i2=0;
    while (size1 > i1){
        if ( arr1[i1] < arr2[i2]){
            result[result_size++] = arr1[i1++];
        } else{
            if ( arr2[i2] < arr1[i1] )
                result[result_size++] = arr2[i2++];
            else{
                i1++; i2++;
            }
        }
        if ( i2 == size2 ){
            for ( ; i1 < size1; i1++)
                result[result_size++] = arr1[i1];
        }
    }

    for ( ; i2 < size2 ; i2++){
        result[result_size++] = arr2[i2];
    }
}

int main(){
    getUncommonValues(arr1,sizeof(arr1)/sizeof(int), arr2,sizeof(arr2)/sizeof(int));
    for (int i =0; i<result_size; i++)
        cout << result[i] <<" ,";

    cout << endl;
    return 0;
}

Note : here the result is stored in global array and has fixed size. This can be resolved in vector directly.