I have two vectors. And I need to remove from vector1 what there is in vector2.
[EDIT: it isn't clear whether this means per-element subtraction as per the link below or set difference]
I use Visual Studio 2010.
There seems to be a method: http://msdn.microsoft.com/en-us/library/system.windows.vector.subtract.aspx
But it somehow doesn't work and even there is no code example.
Could you help me? If no standard method exists, maybe you could suggest how to organize it via loops? Thank you in advance.
#include "stdafx.h";
#include <vector>;
#include <iostream>
using namespace std;
int main ()
{
vector<int> vector1;
vector<int> vector2;
for (int i = 0; i < 10; i++)
{
vector1.push_back (i);
}
for (int i = 0; i < 6; i++)
{
vector2.push_back (i);
}
myvector1 = Subtract(vector1, vector2);
return 0;
}
You should use std::set_difference
: http://en.cppreference.com/w/cpp/algorithm/set_difference
First you will need to sort
your vectors
, since set_difference
operates on sorted ranges. That is, unless they are sorted already (like in your use case).
std::sort(vector1.begin(), vector1.end());
std::sort(vector2.begin(), vector2.end());
Then you call it like this:
std::vector<int> difference;
std::set_difference(
vector1.begin(), vector1.end(),
vector2.begin(), vector2.end(),
std::back_inserter( difference )
);
This will append to difference
those elements found in vector1
that are not found in vector2
.
std::transform(vector1.begin(), vector1.end(), vector2.begin(), vector1.begin(), std::minus<int>())
The 4th argument is the place of the result. It should work even if the size of vectors are different .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With