在将元素添加到 c++ 中的向量之前是否需要检查容量?

发布于 2024-08-30 15:58:13 字数 157 浏览 2 评论 0原文

我是 C++ STL 矢量的新手,很抱歉提前提出一些愚蠢的问题。 :) 在我的程序中,我有一个向量需要存储未知数量的元素。 在向向量添加新元素之前,我是否必须检查向量是否已达到其 max_size ? 当程序尝试向完整向量添加元素时,C++ 编译器会自动抛出异常吗?

非常感谢你,卡西

I am a newbie to c++ STL vectors so sorry for silly questions in advence. :)
In my program, I have a vector which needs to store unknown number of elements.
Do I have to check if the vector has achieved its max_size before adding an new element to it ?
Will a c++ compiler throw an exception automatically when a program tries to add elements to a full vector ?

Thank you very much, Cassie

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

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

发布评论

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

评论(4

芯好空 2024-09-06 15:58:13

如果 std::vector 已达到其最大大小,尝试插入另一个元素将导致底层分配器抛出 std::bad_alloc 异常。

但请注意,向量的最大大小通常非常非常大(例如,可以通过 size_t 除以元素类型的大小来表示的最大值),因此不太可能如果不是不可能的话,您可以在用完可存储向量的连续内存之前达到最大大小。

If the std::vector has reached its max size, attempting to insert another element will result in the underlying allocator throwing a std::bad_alloc exception.

Note, however, that the maximum size for a vector is typically very, very large (e.g., the maximum value that can be represented by size_t divided by the size of the element type), so it is unlikely, if not impossible, for you to reach the maximum size before you run out of contiguous memory in which the vector can be stored.

乖乖哒 2024-09-06 15:58:13

由于您没有包含任何示例代码,因此需要明确的是,这取决于您如何添加。如果您使用push_back(),那么是的,向量将自动扩展。如果您输入类似 v[count++]=value; 的内容,那么您可能会遇到问题,因为这不会检查索引是否在范围内。

Since you didn't include any example code, just to be clear it depends on how you do the adding. If you are using push_back(), then yes, the vector will automatically expand. If you are ding something like v[count++]=value;, then you could run into a problem, as this does not check that the index is in range.

橘虞初梦 2024-09-06 15:58:13

不会。插入元素只会使 vector 中的任何迭代器、引用或元素指针失效。您的插入(几乎)总是会成功。

我说“几乎”是因为如果没有足够的内存来移动底层数组(因为它达到了 max_size - 通常为数百万或数十亿),或者如果构建数组时发生异常,则可能会发生异常新元素。在这些情况下,会引发 C++ 异常。

No. Inserting an element just can invalidate any iterators, references, or pointers to elements in the vector. Your insertion will (nearly) always succeed.

I say "nearly" because an exception could occur either if there's not enough memory to move the underlying array (because it's reached max_size -- typically in the millions or billions), or if an exception occurs constructing the new element. In these cases, a c++ exception is thrown.

谈下烟灰 2024-09-06 15:58:13

不,你不必担心。向量和其他 STL 容器会根据需要自动增长(与普通数组不同)。

No, you don't have to worry. Vectors, and other STL containers automatically grow as needed (unlike ordinary arrays).

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