c++中的匿名数组

Anonymous arrays in C++

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

在C99+中,我可以使用匿名数组和结构体作为复合字量,例如

void f(unsigned char *data);
f((char []){ 42, 15, 33 });

等于

{
    char tmp[] = { 42, 15, 33 };
    f(tmp);
}

在c++中有类似的方法吗?

在c++ 11中,你有std::initializer_list允许类似的事情:

// Declare function
void f(std::initializer_list<int> data);
...
// Call function
f({ 1, 2, 3, 4 });

大多数容器已被修改为采用std::initializer_list,因此您可以使用例如std::vector代替:

// Function declaration, call as before
void f(const std::vector<int>& data);