NoC*_*nde 2 c++ loops range auto
如果我声明:
string s = "ARZ";
Run Code Online (Sandbox Code Playgroud)
然后运行以下代码:
for (auto& c : s) {
cout << (void*)&c << endl;
}
Run Code Online (Sandbox Code Playgroud)
结果将对应于的地址s[0],s[1]和s[2]分别。
如果我删除&并运行:
for (auto c : s) {
cout << (void*)&c << endl;
}
Run Code Online (Sandbox Code Playgroud)
的地址c始终相同。
大概c只是指向向量的指针,它的值sizeof(char)随每个循环而增加,但是我发现很难理解为什么我不需要写*c访问字符串char值的原因。
最后,如果我运行:
for (auto c: s) {
c='?';
cout << c << endl;
}
Run Code Online (Sandbox Code Playgroud)
它打印出3个问号。
我发现很难理解c实际上是什么?
在“ for(auto c:str)”中,c到底是什么?
这是一个局部变量,其作用域是整个for块并具有char类型。
for (auto c : str) { loop_statement }
Run Code Online (Sandbox Code Playgroud)
相当于
{
for (auto __begin = str.begin(), __end = str.end(); __begin != __end; ++__begin) {
auto c = *__begin;
loop_statement
}
}
Run Code Online (Sandbox Code Playgroud)
在某些实现中,在某些情况下,由于cend的生存期在next-iteration的生存期开始之前就已c结束,因此它将在同一位置分配并获得相同的地址。您不能依靠它。
如果您不知道类型,则可以让编译器告诉您:
#include <string>
template <typename T>
struct tell_type;
int main(){
std::string s = "asdf";
for (auto& c : s) {
tell_type<decltype(c)>();
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,没有的定义tell_type,因此将导致以下错误:
error: implicit instantiation of undefined template 'tell_type<char>'
Run Code Online (Sandbox Code Playgroud)
同样
error: implicit instantiation of undefined template 'tell_type<char &>'
Run Code Online (Sandbox Code Playgroud)
为for (auto& ...循环。