llvm.org GIT mirror llvm / 89502f0
add a trivial SmallSet class, which operates on a similar principle to SmallVector. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@33456 91177308-0d34-0410-b5e6-96231b3b80d8 Chris Lattner 13 years ago
1 changed file(s) with 76 addition(s) and 0 deletion(s). Raw diff Collapse all Expand all
0 //===- llvm/ADT/SmallSet.h - 'Normally small' sets --------------*- C++ -*-===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file was developed by Chris Lattner and is distributed under
5 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the SmallSet class.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #ifndef LLVM_ADT_SMALLSET_H
14 #define LLVM_ADT_SMALLSET_H
15
16 #include "llvm/ADT/SmallVector.h"
17
18 namespace llvm {
19
20 /// SmallSet - This maintains a set of unique values, optimizing for the case
21 /// when the set is small (less than N). In this case, the set can be
22 /// maintained with no mallocs.
23 ///
24 /// Note that this set does not guarantee that the elements in the set will be
25 /// ordered.
26 template
27 class SmallSet {
28 SmallVector Vector;
29 typedef typename SmallVector::iterator mutable_iterator;
30 public:
31 SmallSet() {}
32
33 // Support iteration.
34 typedef typename SmallVector::const_iterator iterator;
35 typedef typename SmallVector::const_iterator const_iterator;
36
37 iterator begin() const { return Vector.begin(); }
38 iterator end() const { return Vector.end(); }
39
40 bool empty() const { return Vector.empty(); }
41 unsigned size() const { return Vector.size(); }
42
43 /// count - Return true if the element is in the set.
44 unsigned count(const T &V) const {
45 // Since the collection is small, just do a linear search.
46 for (iterator I = begin(), E = end(); I != E; ++I)
47 if (*I == V)
48 return 1;
49 return 0;
50 }
51
52 /// insert - Insert an element into the set if it isn't already there.
53 void insert(const T &V) {
54 if (count(V)) return; // Don't reinsert if it already exists.
55 Vector.push_back(V);
56 }
57
58 void erase(const T &V) {
59 for (mutable_iterator I = Vector.begin(), E = Vector.end(); I != E; ++I)
60 if (*I == V) {
61 Vector.erase(I);
62 return;
63 }
64 }
65
66 void clear() {
67 Vector.clear();
68 }
69
70 };
71
72
73 } // end namespace llvm
74
75 #endif