c++ - 在 for 循环中声明 vector 运算

标签 c++ for-loop vector

<分区>

考虑这段代码:

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 longsize_t .

通过使用 vector<T>::size_type ,您的代码在不同的实现中保持可移植性。

另见 vector<int>::size_type in C++ .

关于c++ - 在 for 循环中声明 vector 运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15383549/

相关文章:

C++:像使用数组一样使用 std::vectors 是否安全?

mysql - 在 MySQL 中存储矢量坐标

c++ - 从 C src 调用 C++ 函数

c++ - 使用 boost::archive::binary_iarchive 的内存泄漏

java - 如何从扫描仪获取多个输入并将数字分配给一个值?

python - 了解这些 Python for 循环创建列表列表的逻辑

java - 在按钮中添加总计

c++ - C++ 中的整数数组列表<>?

c++ - 如何使用 C 编程从 dbus 传递/返回结构?

Java数组循环方法返回数组中的最后一个值