作为整数数组传递参数
passing arguments as array of integers
struct G{
G&operator()(const int**a)
{
v<<a;
std::copy(v.begin(),v.end(),std::ostream_iterator<int>(std::cout, " "));
return *this;
}
friend std::vector<int>&operator<<(std::vector<int>&v,const int** n);
std::vector<int>v;
};
std::vector<int>&operator<<(std::vector<int>&v,const int** n)
{
v.insert(v.begin(),*n,*n+sizeof(*n)/sizeof(*n[0]));
return v;
}
/// use it
G g;
int v[8]={1,2,3,4,5,6,5,4};
g(&v);
我有两个问题,1. 上面的代码返回错误cannot convert parameter 1 from 'int (*)[8]' to 'const int **'
2. 我想把g传递为g({1,2,3,4,5,6,5,4})而不是g(&v)。但我不知道该怎么做,而且总是怀疑我是否会接受。谢谢你。
如果您知道您将始终使用大小为8的常量数组,
struct G{
G&operator()(int a[8])
{
v.reserve(8);
v.insert(v.begin(), a, a + 8);
std::copy(v.begin(),v.end(),std::ostream_iterator<int>(std::cout, " "));
return *this;
}
std::vector<int>v;
};
/// use it
G g;
int v[8]={1,2,3,4,5,6,5,4};
g(v);
如果没有,你需要传递数组的大小和数组:
struct G{
G&operator()(int* a, int len)
{
v.reserve(len);
v.insert(v.begin(), a, a + len);
std::copy(v.begin(),v.end(),std::ostream_iterator<int>(std::cout, " "));
return *this;
}
std::vector<int>v;
};
/// use it
G g;
int v[8]={1,2,3,4,5,6,5,4};
g(v, sizeof(v) / sizeof(int));
或者,如果您总是要使用编译时数组(从声明它们的作用域)而不是动态数组,
struct G{
template<unsigned int Len>
G& operator()(int (&a)[Len])
{
v.reserve(Len);
v.insert(v.begin(), a, a + Len);
std::copy(v.begin(),v.end(),std::ostream_iterator<int>(std::cout, " "));
return *this;
}
std::vector<int>v;
};
/// use it
G g;
int v[]={1,2,3,4,5,6,5,4};
g(v);
但是请注意,最后一个版本将为您传递给它的每个不同大小的数组生成不同版本的operator()
。
-
&v
是给你数组的地址,当你想要一个指针的地址。试着做const int* x = v
然后g(&x)
。 -
在c++ 0x中,可以这样做:
G& operator()(std::initializer_list<const int>); g({1,2,3,4,5,6,5,4});
相关文章:
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 如何使用Visual Studio 2017在C++中为参数化对象数组使用唯一指针
- 为 NewObjectA() 函数创建 jvalues 的参数数组时出错 - JNI Invocation API
- 估计函数参数数组的维度
- 温度参数数组的内存泄漏
- 如何将值附加到命令行参数数组?
- libpqxx:如何绑定参数数组
- 如何在德尔福中C++参数数组指针算术
- C++函数参数或参数数组
- 将 std::function 代理为需要参数数组的 C 函数
- 分析字符串参数数组
- Pro*C传递参数数组
- OpenCV错误:cvGetSize中的错误参数(数组应该是CvMat或IplImage)
- c++无限参数数组
- 查找命令行参数数组中的元素数
- 如何将目录中所有具有完整路径的文件传递到execv中的参数数组
- ODBC:参数数组-忽略参数
- 使用lambda参数数组