扩展作为内存传递的向量的大小

发布于 2024-07-14 08:56:21 字数 115 浏览 3 评论 0原文

我将向量传递给需要 ac 数组的函数。 它返回它填充的数据量(类似于 fread)。 有没有办法告诉我的向量更改其大小以包含函数传入的数量?

当然,我确保向量有容量()来容纳那么多的数据。

I am passing my vector to a function that expects a c array. It returns the amount of data it filled (similar to fread). Is there a way i can tell my vector to change its size to include the amount that function has passed in?

of course i make sure the vector has the capacity() to hold that amount of data.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

如梦初醒的夏天 2024-07-21 08:56:21

不,没有受支持的方法来“扩展”向量,因此它包含已直接复制的额外值。依赖“容量”来分配可写入的非大小内存绝对不是您应该依赖的。

您应该在调用函数之前调整大小,然后再调整到正确的值,以确保向量具有所需的空间量。 例如

vector.resize(MAX_SIZE);
size_t items = write_array(&(vec[0]), MAX_SIZE)
vector.resize(items);

No, there is no supported way to "expand" a vector so it contains extra values that have been directly copied in. Relying on "capacity" to allocate non-sized memory that you can write to is definitely not something you should rely on.

You should ensure your vector has the required amount of space by resizing before calling the function and then resizing to the correct value afterwards. E.g.

vector.resize(MAX_SIZE);
size_t items = write_array(&(vec[0]), MAX_SIZE)
vector.resize(items);
幸福%小乖 2024-07-21 08:56:21

capacity 仅告诉您保留了多少内存,但它不是向量的大小。

您应该做的是首先将大小调整为所需的最大大小:

vec.resize(maxSizePossible);
size_t len = cfunc(&(vec[0]));
vec.resize(len);

capacity tells you only how much memory is reserved, but it is not the size of the vector.

What you should do is resizes to maximum required size first:

vec.resize(maxSizePossible);
size_t len = cfunc(&(vec[0]));
vec.resize(len);
一个人的旅程 2024-07-21 08:56:21

嗯..
向量.resize(大小);

hmm..
vector.resize(size);
?

半窗疏影 2024-07-21 08:56:21

std::vector 有一个 resize() 方法,以新大小作为参数。 因此,只需使用函数返回的数字来调用它就可以了。

std::vector has a resize() method with the new size as its parameter. So simply calling it with the number returned by your function should be fine.

執念 2024-07-21 08:56:21

std::back_inserter 可能就是您所需要的。 假设您的输入函数能够使用迭代器,请将其传递给 std::back_inserter(myvector)。 这将push_back写入迭代器的所有内容,并根据需要隐式调整向量的大小。

std::back_inserter might be what you need. Assuming your input function is able to work with an iterator, pass it std::back_inserter(myvector). That will push_back everything written to the iterator, and implicitly resize the vector as necessary.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文