blob: d79d386380479fa44eb38fabaae1305bbcb89078 [file] [log] [blame]
Chris Lattneredcea4b2002-02-05 03:35:10 +00001//===-- Support/SetOperations.h - Generic Set Operations ---------*- C++ -*--=//
2//
3// This file defines generic set operations that may be used on set's of
4// different types, and different element types.
5//
6//===----------------------------------------------------------------------===//
7
8#ifndef LLVM_SUPPORT_SET_OPERATIONS_H
9#define LLVM_SUPPORT_SET_OPERATIONS_H
10
11// set_union(A, B) - Compute A := A u B, return whether A changed.
12//
13template <class S1Ty, class S2Ty>
14bool set_union(S1Ty &S1, const S2Ty &S2) {
15 bool Changed = false;
16
17 for (typename S2Ty::const_iterator SI = S2.begin(), SE = S2.end();
18 SI != SE; ++SI)
19 if (S1.insert(*SI).second)
20 Changed = true;
21
22 return Changed;
23}
24
25// set_intersect(A, B) - Compute A := A ^ B
26// Identical to set_intersection, except that it works on set<>'s and
27// is nicer to use. Functionally, this iterates through S1, removing
28// elements that are not contained in S2.
29//
30template <template<class S1ElTy> class S1Ty, class ETy, class S2Ty>
31void set_intersect(S1Ty<ETy> &S1, const S2Ty &S2) {
32 for (typename S1Ty<ETy>::iterator I = S1.begin(); I != S1.end();) {
33 const ETy &E = *I;
34 ++I;
35 if (!S2.count(E)) S1.erase(E); // Erase element if not in S2
36 }
37}
38
39// set_difference(A, B) - Return A - B
40//
41template <class S1Ty, class S2Ty>
42S1Ty set_difference(const S1Ty &S1, const S2Ty &S2) {
43 S1Ty Result;
44 for (typename S1Ty::const_iterator SI = S1.begin(), SE = S1.end();
45 SI != SE; ++SI)
46 if (!S2.count(*SI)) // if the element is not in set2
47 Result.insert(*SI);
48 return Result;
49}
50
51// set_subtract(A, B) - Compute A := A - B
52//
53template <class S1Ty, class S2Ty>
54void set_subtract(S1Ty &S1, const S2Ty &S2) {
55 for (typename S2Ty::const_iterator SI = S2.begin(), SE = S2.end();
56 SI != SE; ++SI)
57 S1.erase(*SI);
58}
59
60#endif