我该如何做这样的some_function({1,1,1,1})
How do I do something like this some_function({1,1,1,1})?
假设我有一个原型为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++变体的扩展。
相关文章:
- 我不知道这条线是做什么的
- 这段代码的最后一行在做什么?
- *(int*)&data[18]在这段代码中实际上做了什么?
- Boost FFT示例-编译时出错,这段代码在做什么
- 这"在比赛中为m,n"做什么?
- a = !5 < a;在这一行代码中究竟做了什么?
- 这条代码线在双方图算法中通过BFS做什么
- 这是循环做什么C++?tempList[j+1]
- 为什么这句话"The expression can be used only as the left-hand operand of a member function call"在 [expr.re
- 标准::地图使用.这是怎么回事?核心转储?我做得不正确?
- 未签名的char *添加了int?这做了什么
- qt c++ 中的这句话是做什么的
- 这是做什么的?C++
- C 运算符在参考vars上,这是做什么的
- 我可以用c++中的模板类来做这件事吗
- 为什么这是部分专业化?(我能做什么?
- 这是在做什么:"input >> 4 & 0x0F"?
- 这条线想做什么
- C++继承和受保护基类成员的访问:用Java风格做这件事是个坏主意吗
- 无法使用统一初始化复制 std::vector<std::function<void ()>>。这是对的吗?