简体   繁体   English

在空的 std::vector 上调用 resize(0) 是否合法?

[英]Is it legal to call resize(0) on an empty std::vector?

I have the following code:我有以下代码:

std::vector<int> v; // v has no elements
int size = getSomeNumber(); // this function may return any number that is >= 0
v.resize(size);

As you can see, getSomeNumber may return any positivie number or 0.如您所见, getSomeNumber可能返回任何正数或 0。

Instead of checking if size > 0 before calling resize , I would rather simply call it immediately.而不是在调用resize之前检查size > 0 ,我宁愿简单地立即调用它。 And in case size is 0, nothing would happen.如果size为 0,则不会发生任何事情。

Is this legal code?这是合法的代码吗?

Indeed it is legal to call resize(0) on an empty std::vector .实际上,在空的std::vector上调用resize(0)是合法的。

Although std::vector::clear does the same thing, and is clearer.虽然std::vector::clear做同样的事情,而且更清晰。

Note that you can regard the behaviour of v.resize(v.size()) to be a no operation.请注意,您可以将v.resize(v.size())的行为视为无操作。 The C++ standard states that the complexity has to be linear (nb not necessarily proportional ) in the difference between the new size and the current size in the cases where the operation doesn't decrease the number of elements. C++ 标准规定,在操作不减少元素数量的情况下,新大小与当前大小之间的差异的复杂性必须是线性的(nb 不一定成比例)。

It's legal, as @Bathsheba said it has the same effect of calling the clear() method.这是合法的,正如@Bathsheba 所说,它与调用clear()方法具有相同的效果。 Also, it is guaranteed no exception is thrown: "If n is less than or equal to the size of the container, the function never throws exceptions (no-throw guarantee)."此外,保证不抛出异常: “如果 n 小于或等于容器的大小,则 function 永远不会抛出异常(不抛出保证)。” ( reference ). 参考)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM