C++——auto keyword

Table of contents

1.Introduction to auto

2. Rules for using auto

3. The practical application value of auto

1.Introduction to auto

In the early days of C/C++, the meaning of auto was: variables modified with auto are local variables with automatic memory . Unfortunately, no one has ever used it. Can you think about why?

In C++11, the standards committee has given auto a new meaning: auto is no longer a storage type indicator, but serves as a new type indicator to instruct the compiler. Variables declared by auto must be compiled by the compiler. Derived from the period . To put it simply: when you define a variable previously, you need to specify the type before the variable. You can use auto without specifying the type and let the value assigned on the right be deduced, as in the example:

int a = 10;
auto b = a;
auto c = 'a';

The type of a here is integer, then it is automatically deduced that the type of b is int, and 'a' is of type char, so naturally c is of type char.

  • Replenish:

Here is another knowledge point: typeid().name . It is specially used to output the type of a variable and returns a string.

  • Code demo:
int TestAuto()
{
	return 10;
}
int main()
{
	const int a = 10;
	auto b = a;
	auto m = &a;
	auto c = 'a';
	auto d = TestAuto();
	cout << typeid(b).name() << endl; // int
	cout << typeid(m).name() << endl; // int const *
	cout << typeid(c).name() << endl; // char 
	cout << typeid(d).name() << endl; // int
	//auto e; 无法通过编译,使用auto定义变量时必须对其进行初始化
	return 0;
}
  • Notice:

When using auto to define a variable, it must be initialized . During the compilation phase, the compiler needs to deduce the actual type of auto based on the initialization expression. Therefore, auto is not a "type" declaration , but a "placeholder" for type declaration . The compiler will replace auto with the actual type of the variable during compilation.

2. Rules for using auto

 1. Auto is used in combination with pointers and references.

When using auto to declare a pointer type, there is no difference between using auto and auto*, but when using auto to declare a reference type, you must add &.

int main()
{
	int x = 10;
	auto a = &x;
	auto* b = &x;
	auto& c = x;
	cout << typeid(a).name() << endl; // int*
	cout << typeid(b).name() << endl; // int*
	cout << typeid(c).name() << endl; // int
	*a = 20;
	*b = 30;
	c = 40;
	return 0;
}
  • 2. Define multiple variables on the same line
void TestAuto()
{
	auto a = 1, b = 2;
	auto c = 3, d = 4.0; // 该行代码会编译失败,因为c和d的初始化表达式类型不同
}
  • 3. auto cannot be used directly to declare arrays
void TestAuto()
{
	int a[] = { 1,2,3 };
	auto b[] = { 4,5,6 }; //err 错误
}
  • 4. In order to avoid confusion with auto in C++98, C++11 only retains the use of auto as a type indicator.
  • 5. The most common advantageous use of auto in practice is to use it in conjunction with the new for loop provided by C++11, which will be discussed later, and lambda expressions.

3. The practical application value of auto

1. When the type is too long and you are too lazy to write it, you can let it be automatically deduced.
When learning containers, you will write code like this: Using auto can simplify the code that previously defined an overly long type and make it automatically determine the type.

#include<map>
#include<string>
int main()
{
	std::map<std::string, std::string>dict;
	dict["sort"] = "排序";
	dict["string"] = "字符串";
//auto意义之一:类型很长时,懒得写,可以让它自动推导
	std::map<std::string, std::string>::iterator it = dict.begin();
	auto it = dict.begin();
	return 0;
}
  • 2. Range-based for loop (C++11)

1. The syntax of range for

In C language, if we want to print a string of data in an array, we can write like this:

void TestFor()
{
	int array[] = { 1, 2, 3, 4, 5 };
	for (int i = 0; i < sizeof(array) / sizeof(int); ++i)
		array[i] *= 2;
	for (int i = 0; i < sizeof(array) / sizeof(int); ++i)
		cout << array[i] << " "; // 2 4 6 8 10
}

For a ranged collection , it is redundant and sometimes error-prone for the programmer to specify the range of the loop. Therefore, range-based for loops were introduced in C++11. The parentheses after the for loop are divided into two parts by the colon ":": the first part is the variable in the range used for iteration, and the second part represents the range being iterated .

So in C++ we can write a loop like this:

void TestFor()
{
	int array[] = { 1, 2, 3, 4, 5 };
	for (int i = 0; i < sizeof(array) / sizeof(int); ++i)
		array[i] *= 2;
	for (auto e : array)
		cout << e << " "; // 2 4 6 8 10
}

This code is the range for, which can be traversed automatically. It will take the data in the array and assign it to e, and automatically judge the end.

  • But now I want to modify the array so that each number in the array is divided by 2. What should I do? Is it like this?

Why don't the modifications as shown in the diagram work? Pay attention to the rules of range for, and assign the data in the array to e in sequence . This also shows that e is a copy of each value in the array, and changes in e will not affect the array. At this point we need to use references. When we give it an alias, the modification of e will affect the original array.

void TestFor()
{
	int array[] = { 1, 2, 3, 4, 5 };
	for (int i = 0; i < sizeof(array) / sizeof(int); ++i)
		array[i] *= 2;
	for (auto e : array)
		cout << e << " "; // 2 4 6 8 10
	cout << endl;
	for (auto& e : array)
		e /= 2;
	for (auto e : array)
		cout << e << " "; //1 2 3 4 5
}
  • Replenish:

(1) Auto in the range for can also be written as int, but it is better to write it as auto. After all, auto can automatically derive the type of the array. If you don’t use auto, you have to set it manually. It is also possible to change e to other variables, but it is not required.

(2) Similar to a normal loop, you can use continue to end this loop, or you can use break to jump out of the entire loop.


2. Conditions for using range for

  • (1) The range of for loop iteration must be determined

For an array, it is the range of the first element and the last element in the array; for a class, the begin and end methods should be provided, and begin and end are the range of the for loop iteration.

Note: There is a problem with the following code because the scope of for is uncertain.

void TestFor(int array[])
{
	for (auto& e : array)
		cout << e << endl;
}

When using range for, it must be an array name. The C language stipulates that the parameter cannot be an array during the transfer process. The formal parameter here is a pointer, so naturally the rule of range for cannot be used.

  • (2) The iterated object must implement ++ and == operations. (As for the issue of iterators, we will talk about it later, but now it’s enough to briefly understand it.

Guess you like

Origin blog.csdn.net/m0_49687898/article/details/131348337