如何在C++中使用auto关键字
How to use auto keyword in C++
我有一个类型为auto
:的C++代码
auto T = reads a JSON
我需要使用打印T
的内容
cout << T << endl;
它不起作用。你能帮我吗?
使用C++11,您可以声明变量或对象,而无需使用auto指定其特定类型。1例如:
auto i = 42; // i has type int
double f();
auto d = f(); // d has type double
用auto声明的变量的类型是从其初始值设定项推导出来的。因此,需要初始化:
自动i;//错误:无法删除i 的类型
允许额外的资格认证。例如:
静态自动增值税=0.19;
当类型是一个相当长和/或复杂的表达式时,使用auto特别有用。例如:
vector<string> v; ... auto pos = v.begin(); // pos has type vector<string>::iterator
auto l = [] (int x) -> bool { // l has the type of a lambda ..., // taking an int and returning a bool };
简而言之,auto可以推断出任何类型。您的程序不工作,因为它可能无法解析JSON或编译器很旧(其中不支持auto。您能特别告诉我您得到的错误吗?
auto
在C++中的意思是"为初始化表达式的类型设置变量类型",在您的情况下,无论"读取JSON"表达式返回什么。您无法将该类型输出到std::cout
,因为operator<<
没有为此类类型定义,可能有许多原因,如未提供运算符、您假设使用其他内容、缺少标头等。解决方案将取决于实际类型。
好!在告诉你如何使用auto
之前,我必须告诉你它是C++11
&通过:-使C++
更加高效
-
减少代码量
-
强制初始化
-
增加泛型(在C++17中)
首先,auto
只有一个作业。它将通过传递给对象的值来推断对象的类型。例如:-
auto x = 5;
这意味着x
是一个值为5的整数。无论何时使用auto
,都必须初始化变量(这是一件好事)&不能对语句中的多个类型使用auto。例如:-
auto x; // illegal ! x isn't initialized so compiler cannot dduce it's type
auto z=5, y=7; // legal because z & y are both integers
auto a=8, ch= 'c'; // illegal ! an integer & a character in a single statement, hence type deduction ambiguity
auto
的精华不在于初始化int
、char
等数据类型。与iterators
一样,它对classes
更方便。例如:-
vector<int> v;
vector<int>::iterator i1 = v.begin();
auto i2 = v.begin(); // see how auto reduces the code length
这在for
循环中更加明显:-
for (vector<int>::iterator i = v.begin(); i!=v.end(); ++i);
可以减少为:-
for (auto i = v.begin(), i!=v.end(); ++i);
如果你对以上内容不满意,那么这可能会激励你使用auto
:-
vector< map <int, vector<string> > >::iterator i1 = v.begin(); // where v is the vector of maps of ints & vectors of strings !!!!
auto i2 = v.begin();
我所说的一般性是通过auto
将值传递给函数。类似:-
void add (auto x, auto y)
{
cout << x+y << 'n';
}
这在当前的标准&已经提出用于C++17。这可能会在不使用templates
的情况下增加函数的通用能力。但是,此语法对于lambda functions
:-是可能的
auto l = [](auto x, auto y) { return x+y; } // legal from C++14 onwards
但是,在lambda中使用大括号时要小心,因为您可能会认为:-
auto x = {5};
是一个整数,但它实际上是一个intializer_list<int>
类型的对象。我可以解释很多关于auto
的事情,但我想现在这已经足够了。
- C++/11 auto 关键字是在更有效时推导参数进行按引用传递,还是始终按值传递?
- auto 关键字在 Dev c++ 中不起作用
- 为什么我需要明确编写"auto"关键字?
- 在C++中使用 auto 关键字
- 在 VS Code 中编码时不能在 C++ 中使用 auto 关键字
- 避免使用 auto 关键字从字面上复制 const 和非 const 的代码?
- 省略C++可变参数 lambda 中的"auto"关键字?
- 我可以在动态知道其类型的模板类对象中使用 auto 关键字吗?我不能在没有初始值设定项的情况下使用 auto 关键字吗?
- 使用 auto 关键字初始化字符数组
- auto*在编译时有用吗?auto关键字足够了吗
- lambda 中的跨平台"auto"关键字用法:integral_constant作为函数参数
- 使用 C++11 auto 关键字声明两个(或多个)变量
- C++11: "auto"关键字会检索到cv限定符吗?我有矛盾的样本
- 为什么 auto 关键字不能与指向函数的指针的初始化列表一起使用?
- 遍历多维向量(使用 Auto 关键字?
- 返回指向 const 数据成员和 'auto' 关键字的 const 指针。有点困惑
- 使用 auto 关键字时不遵守对齐方式 16
- 使用auto关键字填充双索引向量
- C++11中的auto关键字奇怪行为
- 在 C++ 中使用 Lambda 表达式和 auto 关键字时出现问题