Set and subset.

Hello, I had problem on the set and subset. So let say i have:
A = {1, 2, 4 , 6}
B = {1, 7, 9}

is there any method to list out the elements in the B that are not belong to A.
So i expected the output list to be:
7, 9

i tried to understand unordered_set, but still no luck.
You can use std::set_difference to do exactly this.

http://en.cppreference.com/w/cpp/algorithm/set_difference

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <algorithm>
#include <iostream>
#include <iterator>
#include <set>

int main()
{
	std::set<int> A = {1, 2, 4 , 6};
	std::set<int> B = {1, 7, 9};
	std::set<int> C;
	
	std::set_difference(B.begin(), B.end(), 
	                    A.begin(), A.end(),
	                    std::inserter(C, C.begin()));

	for (int i : C)
	{
		std::cout << i << std::endl;
	}
}
thank for your reply. can this be aplied to string array too?
string A[4] = {"cat", "dog", "fish", "bird"};
string B[2] = {"cat", "snake"};

because i still didnt get how the declaration of "set<int>" work. I had run your code too, and it give this error:
set.cpp:13:26: error: in C++98 ‘A’ must be initialised by constructor, not by ‘{...}’
set.cpp:13:26: error: could not convert ‘{1, 2, 4, 6}’ from ‘<brace-enclosed initialiser list>’ to ‘std::set<int>’
set.cpp:14:22: error: in C++98 ‘B’ must be initialised by constructor, not by ‘{...}’
set.cpp:14:22: error: could not convert ‘{1, 7, 9}’ from ‘<brace-enclosed initialiser list>’ to ‘std::set<int>’


Thanks in advance
As far as I can tell, Peter87's code is using C++11 uniform initialisation. Have a look at the std::set constructors (on this site's reference) to see how to construct them without curly braces.
i tried to read the documentation gave by Peter87. so i manage to get the result after i modified the code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>

using namespace std;

int main()
{
	int a[4] = {1, 2, 4 , 6};
	int b[3] = {1, 7, 9};
	
	vector<int>A;
	vector<int>B;
	vector<int>C;
	vector<int>D;

	for (int i = 0; i<5; i++)
	{
		A.push_back(a[i]);
	}
	
	for (int i = 0; i<4; i++)
	{
		B.push_back(b[i]);
	}

	set_difference(B.begin(), B.end(), A.begin(), A.end(), inserter(C, C.begin()));
	cout<<C[0]<<endl;

}


cheers
Or, figure out how to turn on C++1114 on your compiler. If you are not forced to use outdated compiler, chances that you simply did not enble all moder features of the language.
Topic archived. No new replies allowed.