c++ 中auto & 和 auto 和c_str 的一些问题
基本知识:
auto 关键字的推导过程完全处于 compile-time,所以并不会影响程序性能。应该放心大胆的使用。
auto i = 1; // i will become int
auto l = 1LL; // l will become long long
auto d = 1.0; // d will become double
auto f = 1.0f; // f will become float
std::vector<int> ivec{1, 2, 3, 4, 5};
for (auto i : ivec) std::cout << i << " "; // 1 2 3 4 5
1. auto 作用域的问题:比如
int a[4] = {1,2,3,4};
for (auto temp : a){
++temp;
printf("num:%d\n", aa);
}
输出的是:2,3,4,5
并不是1,3
在for内,可以把auto的值 temp 看成是临时变量,无论怎么改变,下一次取数据还是正常的顺序。
2. auto 在遍历string字符串的问题:
auto str = "hello";
str 是什么类型?是std::string.???
实际上,str 此时是 const char *.
所以当你对 str 进行 range for 的时候,就会傻眼。
for (auto c : str) { // error! str 没有 begin() 和 end()
//...
}
上述情况应该如何避免? 用取引用 &
auto& str = "hello";
比如在下面代码里,word前面不加 & 是会报错的。
同时,c_str() 返回的是 const char* 类型的
vector<string> words[2]{"asd", "dfd"};
for (auto &word : words) {
const char *temp = word.c_str();
}