为什么自动类型不能与c++语句中的其他内置类型共存
why auto type cannot coexist with other build-in type in for statement C++
看下面的代码:
vector<int> ivec(10);
for (auto it = ivec.begin(), int i = 0; it != ivec.end(); it++)
{
//body;
}
无法成功编译。当我使用其他内置类型而不是auto时,这将是ok的。例如:
for (int i = 0, double d = 1.0; i < d; i++)
{
//body
}
谢谢。
无法编译,因为在for
循环中声明多个类型是语法错误。
我猜你正在寻找迭代,而跟踪索引?
这是许多方法中的一种:
#include <iostream>
#include <vector>
#include <utility>
using namespace std;
auto main() -> int
{
vector<int> ivec { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };
for (auto p = make_pair(ivec.begin(), 0) ;
p.first != ivec.end() ;
++p.first, ++p.second)
{
cout << "index is " << p.second;
cout << " value is " << *(p.first) << endl;
}
return 0;
}
预期输出:index is 0 value is 10
index is 1 value is 9
index is 2 value is 8
index is 3 value is 7
index is 4 value is 6
index is 5 value is 5
index is 6 value is 4
index is 7 value is 3
index is 8 value is 2
index is 9 value is 1
(注意使用预增量来防止不必要的迭代器副本)
相关文章:
- 内置函数可查看CPP中的成员变量
- 是否有内置方法可以强制转换为不同的基础类型,但保留常量限定符?
- 按字母顺序对字符串中的字母进行排序,而无需使用内置的 sort()
- 将字符串转换为浮点数或整数,而无需使用内置函数(如 atoi 或 atof)
- 如何从 c++ 中类中内置的数组继承
- 如何捕获 C++ 内置异常对象
- macOS 是内置在 clang 编译器中还是内置于 xcode ide 中?
- 将编译器开关添加到 Eclipse CDT 内置编译器设置生成?
- gcc Atomic在gcc 4.1.1中内置了奇怪的行为
- 是否有用于元素部分移位的 simd 指令/内在/内置指令?
- 何时包含内置类型和运算符的标头?
- 基本类型与内置类型有什么区别C++
- 指内置类型的文字
- GLUT 问题:重新声明 c++ 内置类型'wchar_t'时出错
- 像自定义类一样构造的指针(内置类型)如何工作?
- 内置类型与用户定义的类型 C++
- 使用内置函数(或任何其他方法)在C++中对2D数组进行排序
- 为什么自动类型不能与c++语句中的其他内置类型共存
- 以管理员身份从qt运行pnputil(或其他Windows内置)
- 是否存在一个c++函数(内置或其他),可以在不重复操作的情况下给出整数除法和模除法的结果