使用typedef创建对数组的引用。

时间:2021-10-14 21:32:05

I am being asked to make the types of the loop control variables known via a typedef statement. The problem I am having is that I don't know how, or even if it is possible, to make a typedef to a reference to an array of 4 elements.

我被要求通过typedef语句创建循环控制变量的类型。我所面临的问题是,我不知道如何,或者即使有可能,将一个类型定义为一个4个元素数组的引用。

/*
Write a program to print the elements of ia. It should
use a range for to manage the iteration.
*/

int main()
{

int ia[3][4] = {
                {4,3,2,1},
                {1,2,3,4},
                {3,1,4,2}
               };

for (int (&p)[4] : ia)     // This is the line I am talking about
    for(int z : p)
        cout << z;

return 0;
}

I am still very new to programming, and I cannot seem to find an answer to this question. Any advice/help regarding the usage of typedef you can offer would be appreciated.

我对编程还是很陌生的,我似乎找不到这个问题的答案。对于你所能提供的typedef的使用,我们将不胜感激。

2 个解决方案

#1


3  

You write a typedef the same way as you write a variable declaration, except that you replace the variable name with the name you want to give to the type, and you stick typedef in front, hence:

您编写一个typedef的方式与编写变量声明的方式相同,只是将变量名替换为您想要给类型的名称,然后在前面插入typedef,因此:

typedef int (&R)[4];

will declare R to be the type "reference to an array of 4 ints".

将把R声明为“对4个ints数组的引用”。

#2


2  

If you are using at least C++11, which is implied by the range-for statement, you can turn to "using" instead of "typedef". It serves the same uses and more, and it has a less confusing syntax:

如果您使用的至少是c++ 11,这是由range-for语句所暗示的,那么您可以使用“using”而不是“typedef”。它有相同的用途和更多的功能,它的语法不那么令人费解:

// Equivalent declarations
typedef int (&arrayRef)[4];
using arrayRef = int (&)[4];
// Usage
for (arrayRef p : ia) { ... }

Furthermore, with using you can template the declaration itself:

此外,使用您可以模板声明本身:

template<typename T, size_t n>
using arrayRef = T (&)[n];

for (arrayRef<int,4> p : ia) { ... }

#1


3  

You write a typedef the same way as you write a variable declaration, except that you replace the variable name with the name you want to give to the type, and you stick typedef in front, hence:

您编写一个typedef的方式与编写变量声明的方式相同,只是将变量名替换为您想要给类型的名称,然后在前面插入typedef,因此:

typedef int (&R)[4];

will declare R to be the type "reference to an array of 4 ints".

将把R声明为“对4个ints数组的引用”。

#2


2  

If you are using at least C++11, which is implied by the range-for statement, you can turn to "using" instead of "typedef". It serves the same uses and more, and it has a less confusing syntax:

如果您使用的至少是c++ 11,这是由range-for语句所暗示的,那么您可以使用“using”而不是“typedef”。它有相同的用途和更多的功能,它的语法不那么令人费解:

// Equivalent declarations
typedef int (&arrayRef)[4];
using arrayRef = int (&)[4];
// Usage
for (arrayRef p : ia) { ... }

Furthermore, with using you can template the declaration itself:

此外,使用您可以模板声明本身:

template<typename T, size_t n>
using arrayRef = T (&)[n];

for (arrayRef<int,4> p : ia) { ... }