作为整数数组传递参数

passing arguments as array of integers

本文关键字:参数 数组 整数      更新时间:2023-10-16
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()

  1. &v是给你数组的地址,当你想要一个指针的地址。试着做const int* x = v然后g(&x)
  2. 在c++ 0x中,可以这样做:

    G& operator()(std::initializer_list<const int>);
    g({1,2,3,4,5,6,5,4});