使数组成为 c++ 函数的可选参数

Make an array an optional parameter for a c++ function

本文关键字:参数 函数 c++ 数组      更新时间:2023-10-16

在 c++ 中,你可以像这样将参数设置为可选:

void myFunction(int myVar = 0);

如何使用数组执行此操作?

void myFunction(int myArray[] = /*What do I put here?*/);

您可以使用nullptr或指向全局 const 数组的指针来表示默认值:

void myFunction(int myArray[] = nullptr ) {
                             // ^^^^^^^
}

这是因为当用作函数参数时int myArray[]类型调整为int*指针。

默认参数必须具有静态链接(例如,是全局参数)。下面是一个示例:

#include <iostream>
int array[] = {100, 1, 2, 3};
void myFunction(int myArray[] = array)
{
    std::cout << "First value of array is: " << myArray[0] << std::endl;
    // Note that you cannot determine the length of myArray!
}
int main()
{
    myFunction();
    return 0;
}

如果默认数组足够小(注意:它可以小于实际数组类型的大小),因此复制它不是问题,那么(自 C++11 以来)std::array可能是最具表现力的"C++式"风格(正如 Ed Heal 在评论中暗示的那样)。除了每个无参数f()调用的复制负担之外,使用默认值,数组本身具有与内置类 C 数组相同的性能属性,但它不需要一个笨拙的、单独定义的默认变量:

#include <array>
// Just for convenience:
typedef std::array<int, 3> my_array;
void f(const my_array& a = {1, 2, 3});

(注意:通过 const ref. 传递至少在那些明确传递参数的情况下会避免复制。

好吧,在现代C++ 17 中,您可以使用std::optional.

std::optional<std::array<int,4>> oa;
// ...
if ( oa )
{
    // there is content in oa
    *oa // get the content
}
else
{
    // there is no content inside oa
}

我使用 std::array 作为数组的表示,但您也可以使用原始数组、向量等。