<分区>
考虑这段代码:
vector<double> student_grades(20);
for (vector<double>::size_type i = 0; i < student_grades.size(); i++)
{
cout << i << endl;
}
以这种方式声明 i
而不是仅仅声明 int i = 0
到底有什么不同?
<分区>
考虑这段代码:
vector<double> student_grades(20);
for (vector<double>::size_type i = 0; i < student_grades.size(); i++)
{
cout << i << endl;
}
以这种方式声明 i
而不是仅仅声明 int i = 0
到底有什么不同?
最佳答案
What exactly is different about declaring i this way instead of just int i = 0?
它确保使用正确的类型 - 你假设 vector<T>::size_type
始终与 int
相同,但这个假设是不正确的。根据实现的不同,它也可能类似于 unsigned int
。 , long
, unsigned long
或 size_t
.
通过使用 vector<T>::size_type
,您的代码在不同的实现中保持可移植性。
关于c++ - 在 for 循环中声明 vector 运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15383549/