本文介绍了为什么我们有std :: string :: npos但没有std :: vector :: npos?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用-1表示尚未计算的大小:

I would like to use -1 to indicate a size that has not yet been computed:

std::vector<std::size_t> sizes(nResults, -1);

我想知道为什么没有一种更具表现力的方式:

and I was wondering why isn't there a more expressive way:

std::vector<std::size_t> sizes(nResults, std::vector<std::size_t>::npos);


推荐答案

来自:

... std :: size_t可以存储
理论上可能是任何类型的对象的最大大小...

...std::size_t can store the maximum size of a theoretically possible object of any type...

size_t 是无符号的,不能表示-1。实际上,如果您尝试将大小设置为-1,则实际上是将它们设置为 size_t 可表示的最大值。

size_t is unsigned, and can't represent -1. In reality if you were to attempt to set your sizes to -1, you would actually be setting them to the maximum value representable by a size_t.

因此,您不应使用 size_t 来表示除值之外还包括类型的可能大小的值表示尚未计算任何大小,因为在可能大小范围之外的任何值都不能用 size_t 表示。

Therefore you should not use size_t to represent values which include the possible size of a type in addition to a value indicating that no size has been computed, because any value outside the set of possible sizes can not be represented by a size_t.

您应该使用其他类型,该类型能够表达您希望表示的所有可能值。这是一种可能性:

You should use a different type which is capable of expressing all of the possible values you wish to represent. Here is one possibility:

struct possibly_computed_size_type
{
    size_t size;
    bool is_computed;
};

当然,您可能会想要一个更具表现力的解决方案,但重点是至少 possfully_computed_size_type 能够存储我们希望表达的所有可能值。

Of course, you'll probably want a more expressive solution than this, but the point is that at least possibly_computed_size_type is capable of storing all of the possible values we wish to express.

一种可能性是使用可选类型。 可选类型可以表示该类型的值的范围,还有一个附加值,表示对象无值。

The standard library also provides an optional type as an experimental feature. Here is an example I created using this type:http://ideone.com/4J0yfe

这篇关于为什么我们有std :: string :: npos但没有std :: vector :: npos?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 14:27