1 //===-- llvm/ADT/SortedVector.h ---------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #ifndef LLVM_ADT_SORTEDVECTOR_H
11 #define LLVM_ADT_SORTEDVECTOR_H
16 #include "llvm/Support/raw_ostream.h"
20 /// \brief Lazily maintains a sorted and unique vector of elements of type T.
21 template<typename T, typename CMP = std::less<T>>
24 typedef typename std::vector<T> VectorType;
25 typedef typename VectorType::iterator iterator;
26 typedef typename VectorType::const_iterator const_iterator;
32 void doCheck() const {
33 assert(IsSorted && "Unsorted SortedVector access; call sortUnique prior.");
37 /// \brief Appends Entry to the sorted unique vector; sets the IsSorted flag
38 /// to false if appending Entry puts Vector into an unsorted state.
39 void insert(const T &Entry) {
41 Vector.push_back(Entry);
43 // Vector is sorted and Entry is a duplicate of the previous so skip.
44 if (IsSorted && Entry == Vector.back())
47 IsSorted &= (CMP()(Vector.back(), Entry));
48 Vector.push_back(Entry);
51 // \brief Sorts and uniques Vector.
56 std::sort(Vector.begin(), Vector.end());
57 Vector.erase(std::unique(Vector.begin(), Vector.end()), Vector.end());
61 /// \brief Tells if Entry is in Vector without relying on sorted-uniqueness.
62 bool has(T Entry) const {
64 return std::binary_search(Vector.begin(), Vector.end(), Entry);
66 return std::find(Vector.begin(), Vector.end(), Entry) != Vector.end();
69 /// \brief Returns a reference to the entry with the specified index.
70 const T &operator[](unsigned index) const {
71 assert(index < size() && "SortedVector index is out of range!");
76 /// \brief Return an iterator to the start of the vector.
79 return Vector.begin();
82 /// \brief Returns const iterator to the start of the vector.
83 const_iterator begin() const {
85 return Vector.begin();
88 /// \brief Returns iterator to the end of Vector.
94 /// \brief Returns const iterator to the end of Vector. Assert if unsorted.
95 const_iterator end() const {
100 /// \brief Erases Vector at position. Asserts if Vector is unsorted.
101 iterator erase(iterator position) {
103 return Vector.erase(position);
106 /// \brief Erases Vector entirely.
109 return Vector.erase();
112 /// \brief Returns number of entries in Vector; asserts if it is unsorted.
113 size_t size() const {
115 return Vector.size();
118 /// \brief Returns true if Vector is empty.
120 return Vector.empty();
123 /// \brief Clears all the entries.
130 } // End of namespace llvm
132 #endif // LLVM_ADT_SORTEDVECTOR_H