File: FixedSizeVector.h

package info (click to toggle)
snap-aligner 1.0.0%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 4,988 kB
  • sloc: cpp: 36,500; ansic: 5,239; python: 227; makefile: 85; sh: 28
file content (72 lines) | stat: -rw-r--r-- 1,459 bytes parent folder | download | duplicates (5)
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#pragma once

#include "exit.h"
#include "Error.h"

//
// A fixed-size vector that does not perform any memory allocation.
//
template<typename V>
class FixedSizeVector
{
public:
    FixedSizeVector(int capacity_ = 16): entries(NULL), curSize(0) {
        reserve(capacity_);
    }

    // Create a fixed size vector initialized to size copies of an initialValue
    FixedSizeVector(int size, V initialValue): entries(NULL), curSize(0) {
        reserve(size);
        for (int i = 0; i < size; i++) {
            push_back(initialValue);
        }
    }

    ~FixedSizeVector() {
        delete[] entries;
    }

    void reserve(int capacity) {
        if (entries != NULL) {
            if (curSize > 0) {
                WriteErrorMessage("reserve() called on a non-empty FixedSizeVector\n");
                soft_exit(1);
            }
            delete[] entries;
        }
        this->capacity = capacity;
        entries = new V[capacity];
    }

    void clear() {
        curSize = 0;
    }

    int size() {
        return curSize;
    }

    inline void push_back(const V& value) {
        _ASSERT(curSize < capacity);
        entries[curSize++] = value;
    }

    inline V& operator[] (int index) {
        return entries[index];
    }

    typedef V *iterator;

    iterator begin() {
        return entries;
    }

    iterator end() {
        return entries + curSize;
    }

private:
    V *entries;
    int capacity;
    int curSize;
};