std :: size_t或std :: vector< Foo> :: size_type? [英] std::size_t or std::vector<Foo>::size_type?
问题描述
当我在std::vector<Foo>
(或每个具有随机访问迭代器的容器)上循环时,我使用无符号整数变量i
.如果要遵守规范,应该使用std::size_t
还是容器本身指定的类型:std::vector<Foo>::size_type
吗?
When I loop on a std::vector<Foo>
(or every container having random access iterator) I use an unsigned integer variable i
. If I want to respect the norm, should I use std::size_t
or the type given by the container itself : std::vector<Foo>::size_type
?
如果出于可读性原因选择了std::size_t
,可以确定std
名称空间中每个容器的每个实现都将std::size_t
用作size_type
吗?
If I chose std::size_t
(for readability reasons), can I be sure that every implementation of every container in std
namespace uses std::size_t
as size_type
?
注意:出于兼容性原因,我仅使用C ++ 98.
Note : I use C++98 only (for compatibility reasons).
推荐答案
std::vector<Foo>::size_type
与std::size_t
相同并不是不必要.即使对于C ++ 11也是如此.
It is not necessarily true that std::vector<Foo>::size_type
is the same as std::size_t
. This is true even for C++11.
但就我个人而言,无论类型如何,我都将std::size_t
用于std::vector
索引.
But personally I use std::size_t
for a std::vector
index irrespective of the type.
如果您特别勤奋,则可以始终使用静态断言.显然,static_assert
是C ++ 98以后的新增内容,但是按照该标准,您可以使用类似
You could always use a static assertion if you're feeling particularly diligent. Obviously static_assert
is a later addition beyond what's in C++98, but in that standard you could use something like
static char wrong_size_1[1 + sizeof(std::size_t) - sizeof(std::vector<Foo>::size_type)];
static char wrong_size_2[1 - sizeof(std::size_t) + sizeof(std::vector<Foo>::size_type)];
如果类型类型的大小不同,则会导致编译时失败.
which would induce compile time failures if type types are not the same size.
这篇关于std :: size_t或std :: vector< Foo> :: size_type?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!