简体   繁体   English

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

[英]Make an array an optional parameter for a c++ function

In c++, you can make a parameter optional like this:在 C++ 中,您可以将参数设为可选,如下所示:

void myFunction(int myVar = 0);

How do you do that with an array?你如何用数组做到这一点?

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

You can use a nullptr or a pointer to a global const array to denote the default value:您可以使用nullptr或指向全局常量数组的指针来表示默认值:

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

This is because int myArray[] is type adjusted to a int* pointer when used as function parameter.这是因为int myArray[]在用作函数参数时被类型调整为int*指针。

The default argument must have static linkage (eg be a global).默认参数必须具有静态链接(例如是一个全局链接)。 Here's an example:下面是一个例子:

#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;
}

If the default array is small enough (note: it can be smaller than the size of the actual array type), so that copying it is not an issue, then (since C++11) std::array is probably the most expressive, "C++-ish" style (as Ed Heal hinted in a comment).如果默认数组足够小(注意:它可以小于实际数组类型的大小),因此复制它不是问题,那么(C++11 起) std::array可能是最具表现力的, “C++-ish”风格(正如 Ed Heal 在评论中暗示的那样)。 Apart from the copy-init burden on each argument-less f() call, using the default, the array itself has the same performance properties as built-in C-like arrays, but it doesn't need an awkward, separately defined default variable:除了每个无参数f()调用的 copy-init 负担外,使用默认值,数组本身具有与内置的类 C 数组相同的性能属性,但它不需要笨拙的、单独定义的默认值变量:

#include <array>

// Just for convenience:
typedef std::array<int, 3> my_array;

void f(const my_array& a = {1, 2, 3});

(NOTE: passing by const ref. avoids the copy at least for those cases, where you do pass an argument explicitly.) (注意:通过 const ref. 至少在那些你明确传递参数的情况下避免了复制。)

Well, in modern C++ 17 you can use std::optional .好吧,在现代 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
}

I used std::array as my representation of the array but you could just as well use raw arrays, vectors, whatever.我使用std::array作为std::array表示,但您也可以使用原始数组、向量等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM