問題描述
在C++ Primer
一書的第 (3) 章中,有以下 for 循環(huán)將向量中的元素重置為零.
為什么使用 vector
?我們不能說 int ix = 0
嗎?在第二種形式上使用第一種形式有什么好處?
謝謝.
C++ 標(biāo)準(zhǔn)說,
<塊引用>size_type |無符號整數(shù)類型 |可以表示最大對象的大小的類型分配模型
然后補充,
<塊引用>容器的實現(xiàn)在本國際中描述的標(biāo)準(zhǔn)允許假設(shè)他們的分配器模板參數(shù)滿足以下兩個附加條件超出表 32 中的要求.
- typedef 成員指針、const_pointer、size_type 和差異類型是需要分別為 T*、T const*、size_t 和 ptrdiff_t
所以很可能,size_type
是 size_t
的 typedef.
標(biāo)準(zhǔn)真正將其定義為,
所以需要注意的最重要的幾點是:
size_type
是unsigned
整數(shù),而int
不是 必然未簽名
.:-)- 它可以表示最大的索引,因為它是無符號的.
In the C++ Primer
book, Chapter (3), there is the following for-loop that resets the elements in the vector to zero.
Why is it using vector<int>::size_type ix = 0
? Cannot we say int ix = 0
? What is the benefit of using the first form on the the second?
Thanks.
The C++ Standard says,
size_type | unsigned integral type | a type that can represent the size of the largest object in the allocation model
Then it adds,
Implementations of containers described in this International Standard are permitted to assume that their Allocator template parameter meets the following two additional requirements beyond those in Table 32.
- The typedef members pointer, const_pointer, size_type, and difference_type are required to be T*,T const*, size_t, and ptrdiff_t, respectively
So most likely, size_type
is a typedef of size_t
.
And the Standard really defines it as,
So the most important points to be noted are :
size_type
isunsigned
integral, whileint
is not necessarilyunsigned
. :-)- it can represent the largest index, because it's unsigned.
這篇關(guān)于C++ for 循環(huán) - size_type 與 size_t的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!