Add and use List<T>::IsEmpty, range-for, etc. NFC.

Changes resemble those already made to IdList.
pull/459/head
Ryan Pavlik 2019-05-22 16:48:40 -05:00 committed by whitequark
parent 0bb6a348e3
commit 1b97a006e9
1 changed files with 31 additions and 31 deletions

View File

@ -205,9 +205,11 @@ public:
template <class T> template <class T>
class List { class List {
public: public:
T *elem; T *elem = nullptr;
int n; int n = 0;
int elemsAllocated; int elemsAllocated = 0;
bool IsEmpty() const { return n == 0; }
void ReserveMore(int howMuch) { void ReserveMore(int howMuch) {
if(n + howMuch > elemsAllocated) { if(n + howMuch > elemsAllocated) {
@ -242,33 +244,32 @@ public:
} }
T *First() { T *First() {
return (n == 0) ? NULL : &(elem[0]); return IsEmpty() ? nullptr : &(elem[0]);
} }
const T *First() const { const T *First() const {
return (n == 0) ? NULL : &(elem[0]); return IsEmpty() ? nullptr : &(elem[0]);
} }
T *NextAfter(T *prev) { T *NextAfter(T *prev) {
if(!prev) return NULL; if(IsEmpty() || !prev) return NULL;
if(prev - elem == (n - 1)) return NULL; if(prev - First() == (n - 1)) return NULL;
return prev + 1; return prev + 1;
} }
const T *NextAfter(const T *prev) const { const T *NextAfter(const T *prev) const {
if(!prev) return NULL; if(IsEmpty() || !prev) return NULL;
if(prev - elem == (n - 1)) return NULL; if(prev - First() == (n - 1)) return NULL;
return prev + 1; return prev + 1;
} }
T *begin() { return &elem[0]; } T *begin() { return IsEmpty() ? nullptr : &elem[0]; }
T *end() { return &elem[n]; } T *end() { return IsEmpty() ? nullptr : &elem[n]; }
const T *begin() const { return &elem[0]; } const T *begin() const { return IsEmpty() ? nullptr : &elem[0]; }
const T *end() const { return &elem[n]; } const T *end() const { return IsEmpty() ? nullptr : &elem[n]; }
const T *cbegin() const { return &elem[0]; } const T *cbegin() const { return begin(); }
const T *cend() const { return &elem[n]; } const T *cend() const { return end(); }
void ClearTags() { void ClearTags() {
int i; for(auto & elt : *this) {
for(i = 0; i < n; i++) { elt.tag = 0;
elem[i].tag = 0;
} }
} }
@ -281,21 +282,20 @@ public:
} }
void RemoveTagged() { void RemoveTagged() {
int src, dest; auto newEnd = std::remove_if(this->begin(), this->end(), [](T &t) {
dest = 0; if(t.tag) {
for(src = 0; src < n; src++) { return true;
if(elem[src].tag) {
// this item should be deleted
} else {
if(src != dest) {
elem[dest] = elem[src];
} }
dest++; return false;
});
auto oldEnd = this->end();
n = newEnd - begin();
if (newEnd != nullptr && oldEnd != nullptr) {
while(newEnd != oldEnd) {
newEnd->~T();
++newEnd;
} }
} }
for(int i = dest; i < n; i++)
elem[i].~T();
n = dest;
// and elemsAllocated is untouched, because we didn't resize // and elemsAllocated is untouched, because we didn't resize
} }