我该如何做这样的some_function({1,1,1,1})

How do I do something like this some_function({1,1,1,1})?

本文关键字:function 何做这 some      更新时间:2023-10-16

假设我有一个原型为int func(int * a)的函数,它接受一个数组作为参数。

如何在编译器不到处显示错误的情况下做到这一点:func({1,1,1,1})

像这样:

int func(int * a);
void somewhere_else()
{
    int arr[4] = { 1, 1, 1, 1 };
    func(arr);
}

不要使用原始数组,当然也不要将指向它们的指针传递到函数中。哇!我们已经不是1975年了。

#include <cstddef>
#include <iostream>
#include <vector>
void func(std::vector<int> const& v) {
   for (std::size_t i = 0; i < v.size(); i++)
      std::cout << v[i] << " ";
}
int main() {
   func({ 1, 2, 3, 4 });
}
// Output: "1 2 3 4 "

这需要一个符合C++11某些特性的编译器。即初始值设定项列表。

您可以使用std::initializer_list:

int func(std::initializer_list<int> a) {
  // do something with a here
}

或者,您可以编写一个使用std::initializer_list的包装器(如果由于某种原因无法更改原始函数):

int func_wrapper(std::initializer_list<int> a) {
  std::vector<int> b = a;
  func(b.data());
}

实现这一点的一种方法是

 #include <iostream>
 #include <stdio.h>

  void abc (int *a,int z)
  {
   int m= z/sizeof(*a);    
   for(int i=0;i<m;i++)
      {
        std::cout<<"values " <<*a<<"n";
        a++;
      }     
  }
 int main()
 {
   int ar[]={11,12,13,14,15,1166,17};
   std::cout << sizeof(ar)<<"sizen";
   abc(ar,sizeof(ar));   
   getchar();
 }

在这种情况下,你不需要担心尺寸和所有的问题。如果int ar[3]={1,2,3},如果您尝试将NULL搜索为第三位由元素3占据

您只需要一个(int[]) cast:

#include <iostream>
static void f (int* a) {
  while (*a) std::cout << *a++ << "n" ;
  }
int main() {
  f ((int[]){1,2,3,4,0}) ;
  }

该代码输出

1
2
3
4

它在C语言中也能工作——请参阅这个表意链接。

更新添加:我发布了一个关于这个结构合法性的新问题,如果你对这类事情感兴趣,Mat的回答值得一读。简而言之,它似乎只在C99中有效,但一些编译器允许它作为所有C/C++变体的扩展。