我如何使用 Arduino IDE 定期附加到数组?

How do I periodically append to an array using the Arduino IDE?

我正在尝试附加用户通过串行监视器输入的浮点值。我需要将这些值按顺序存储在数组中,即每次我得到一个值时,我都必须将它附加到数组中。

A​​rduino 没有开箱即用的动态数据结构(字符串除外)。

您可以从网上下载通用容器的开源实现。这是一个:https://github.com/dhbikoff/Generic-C-Library/blob/master/vector.h

此外,这里有一个简单的linked-list/vector我把自己实现为一个玩具项目。

注意动态内存。内存碎片会导致你的草图随机崩溃(我已经发生过几次)。

template <typename T>
struct SimpleVector {
    struct SimpleVectorNode {
        T* m_value = NULL;
        SimpleVectorNode* m_next = NULL;

        SimpleVectorNode() {

        }

        SimpleVectorNode(T val) {
            m_value = new T(val);
            m_next = NULL;
        }
    };
    int m_size = 0;
    SimpleVectorNode* m_head = new SimpleVectorNode;

    void AddValue(T val) {
        ++m_size;
        SimpleVectorNode* end = m_head;
        while (end->m_next != NULL) {
            end = end->m_next;
        }
        end->m_next = new SimpleVectorNode(val);
    }

    SimpleVectorNode* Seek(int index) {
        SimpleVectorNode* res = m_head;
        while (index >= 0) {
            --index;
            res = res->m_next;
        }
        return res;
    }

    T& Get(int index) {
        return *(Seek(index)->m_value);
    }

    void Delete(int index) {
        SimpleVectorNode* preDel = Seek(index - 1);
        SimpleVectorNode* toDel = preDel->m_next;
        preDel->m_next = toDel->m_next;
        delete toDel->m_value;
        delete toDel;
        --m_size;
    }

    int GetSize() {
        return m_size;
    }

    int IndexOf(T val) {
        SimpleVectorNode* pNode = m_head->m_next;
        for (int i = 0; i < m_size; ++i) {
            if (pNode->m_value == val) {
                return i;
            }

            pNode = pNode->m_next;
        }

        return -1;
    }

    bool Contains(T val) {
        return IndexOf(val) >= 0;
    }

    ~SimpleVector() {
        while (m_size > 0) {
            Delete(0);
        }

        delete m_head;
    }
};