# 快速创建与销毁 Vector 对象实例

### 如何使用 Vector Helper？

Vector Helper 模块的所有函数与数据类型均声明在 `vector_helper.h` 标头文件中，您只需要在您项目中需要使用 Vector Helper 模块的代码文件中包含 `vector_helper.h` 即可。

{% code title="C/C++" %}

```cpp
#include "vector_helper.h"
```

{% endcode %}

{% hint style="warning" %}
您应该在包含您项目所需的 C/C++ 标头之后再包含 vector\_helper.h
{% endhint %}

### 什么是 Vector 对象实例？

每个 Vector Array 均被抽象描述为 Vector 对象实例，而每个 Vector 对象实例均由 `Vector` 类型所表示，而使用该类型定义的变量均为指针，被抽象描述为 Vector 对象实例描述符，该类型被定义在 `vector_helper.h` 中。

{% code title="C" %}

```c
typedef struct _VectorContext
{
	size_t current_element_count;
	size_t last_reserved_element_count;
	size_t max_element_count;
	size_t current_alloc_count;
	size_t current_alloc_memory_size;
	size_t single_element_size;
	void** element;
} VectorContext, *Vector;
```

{% endcode %}

{% content-ref url="../apis/struct" %}
[struct](https://smallso.gitbook.io/vector/apis/struct)
{% endcontent-ref %}

在您使用 Vector Helper API 时，均需要提供 Vector 对象实例描述符。

{% hint style="warning" %}
除非必要，为了确保 Vector 对象实例完整性，您不应该直接通过 Vector 对象实例描述符指针变量访问 VectorContext 数据结构的成员，应调用 Vector Helper API。
{% endhint %}

### 如何创建与销毁 Vector 对象实例？

您可以通过调用 Vector Helper API 来快速创建一个 Vector 对象实例：

{% code title="C" %}

```c
Vector vector_object = vector_helper_create_object(sizeof(int), 1, 99);
```

{% endcode %}

通过上述代码，我们快速创建了一个 Vector 对象实例，并得到了该 Vector 对象实例的描述符，它包含一个 Vector Int 数组。单个元素大小为 `sizeof(int)`，初始预留 1 个元素大小的容量，最多允许存放 99 个元素。当然，若您不希望设置最大元素个数，可以将最后一个参数设置为 `VECTOR_NO_MAX_ELEMENT` 宏。

{% hint style="info" %}
建议在创建 Vector 对象实例时，预估您可能存放的元素个数，并合理设置初始预留元素数量，这可能会减少内存分配器的运行次数，提升元素存取性能。请注意，初始预留元素个数为预留可容纳指定元素个数的容量（也即内存），并非使用空元素进行填充。
{% endhint %}

现在我们尝试销毁它：

{% code title="C" %}

```c
if(vector_object)
{
    vector_helper_destroy_object(vector_object);
    vector_object = NULL;
}
```

{% endcode %}

现在，我们已销毁了由 `vector_helper_create_object` 创建的 Vector 对象实例和描述符。

{% hint style="warning" %}
值得注意的是，变量 vector\_object 也即 Vector 对象实例描述符所指向的 Vector 对象实例已被销毁，因此该描述符已经不可用（无效指针），应该使用 NULL 赋值。
{% endhint %}

{% content-ref url="../apis/object" %}
[object](https://smallso.gitbook.io/vector/apis/object)
{% endcontent-ref %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://smallso.gitbook.io/vector/learn/1.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
