summaryrefslogtreecommitdiffstats
path: root/variablearray.cpp
blob: c1d0503e309b03f86e216b0ab3b5f85fb9ee0ed4 (plain)
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
73
74
75
76
77
78
79
80
81
#include "variablearray.h"
#include <algorithm> /* for find() */

VariableArray::VariableArray() : arr(/* ARR_STARTING_SIZE */)
{
}

VariableArray::VariableArray(const VariableArray& array) : Collection(array), arr(array.arr) /* ha! */
{
}

VariableArray& VariableArray::operator=(const Collection& rhs)
{
    this->arr = dynamic_cast<const VariableArray *>(&rhs)->arr; /* use vector's copy ctor */
    this->size_ = rhs.get_size();
    return *this;
}

VariableArray::~VariableArray()
{
}

void VariableArray::add(int n)
{
    this->arr.push_back(n);
    this->size_++;
}

bool VariableArray::remove(int n)
{
    std::vector<int>::iterator pos = std::find(this->arr.begin(), this->arr.end(), n);
    if (pos != this->arr.end())
    {
        this->arr.erase(pos); /* kind of slow, since elements will get shifted */
        this->size_--;
        return true;
    }
    else
        return false;
}

int VariableArray::operator[](const int i)
{
    /* invalid accesses */
    if (!this->size_ || i < 0 || i+1 > this->size_)
        return -1;

    return this->arr[i];
}

VariableArray *VariableArray::copy(void)
{
    VariableArray *ret = new VariableArray(*this);
    return ret;
}

void VariableArray::iterate(void (*callback)(int *))
{
    std::vector<int>::size_type i;
    for (i = 0; i != this->arr.size(); ++i)
        callback(&this->arr[i]);
}

bool VariableArray::contains(int n) const
{
    return (std::find(this->arr.begin(), this->arr.end(), n) != this->arr.end());
}

std::string VariableArray::print(void) const
{
    std::stringstream sstm;
    std::vector<int>::const_iterator iter = this->arr.begin();
    while (iter != this->arr.end())
    {
        sstm << *iter << " ";
        iter++;
    }

    return sstm.str();
}