考虑到这段代码:
vector<double> student_grades(20);
for (vector<double>::size_type i = 0; i < student_grades.size(); i++)
{
    cout << i << endl;
}
i以这种方式声明而不是 just到底有什么不同int i = 0?
以这种方式声明 i 而不是仅仅声明 int i = 0 到底有什么不同?
它确保使用正确的类型 - 您假设它vector<T>::size_type始终与 相同int,但这种假设是不正确的。根据实现,它也可能是unsigned int,或.longunsigned longsize_t
通过使用vector<T>::size_type,您的代码在不同的实现中保持可移植性。
size_type是向量类中的 typedef,它使vector类有机会决定使用什么类型进行索引。int具有 2^31 的最大值(通常,但不能保证 - 我认为保证至少为 32767)。由于有时我们需要大于 20 亿个项目的向量 [诚然不是那么频繁,我怀疑],因此由类本身指定类型很有用。
这种类型保证覆盖vector实现本身可以处理的范围。它不会太大[如果你选择long long在 32 位系统上使用,它会比你需要的大],也不会太小。当然,如果你知道你只会有 10 件物品,那可能没关系。
It is also almost always a unsigned type. In some cases, that makes the indexing of arrays more efficient, which also helps performance a tiny bit.
vector<T>::size_type是 的static成员std::vector。我不知道为什么有人会使用它,因为它可能会导致混乱,我猜。看这里,他已经在 SO 上回答了。