不确定如何命名这个问题,所以如果听起来不对或有欺骗性,请原谅我。我有一个以前从未遇到过的问题。基本上,当我必须将结构放入函数而不创建实际结构(只需要使用值)时,我会这样做:
struct a{
int x,y,z;
};
void function(a x){ ... }
void main(void){
function(a(34,64,75));
}
但是,现在我需要在该结构中使用一个数组,所以它看起来像..
struct a{
int x[5];
};
void function(a x){ ... }
void main(void){
function(a(????));
}
而且我不知道如何在不使用实际变量的情况下正确初始化它。只是有些不方便,但我想知道这个问题的答案。我尝试过搜索和暴力破解我的方式,但我做得不好。
感谢帮助
编辑:我的问题有很多复杂之处,这让很多人对我的不周到感到不安。首先,我指的不是 C++ 模板,而是这个词的实际含义,抱歉我的英语不好。 我会尝试更好地解释自己(尝试):我想做的是省略为特定函数创建结构变量的用法,并在调用该函数时自己手动定义结构成员,正如您在第一个中看到的示例..但是,在第二个示例中,我真正要问的是如何在数组中手动定义所述结构的成员。我再次为我第一次发布这个问题时的所有错误道歉
最佳答案
我想您使用的是 C++。如果我正确理解你的问题,你想在不使用中间变量的情况下初始化一个数组。在这种情况下,您需要将适当的构造函数添加到您的结构中。
以下代码将执行此操作。但是请注意,您需要最新的编译器,例如 GCC 版本 (>= 4.6),并且您应该编译为 g++ -std=c++11 file.cpp。
#include <iostream>
#include <initializer_list>
#include <algorithm>
using namespace std;
struct s{
int x[5];
// constructor 1. a variant using 'initializer_list'
s(initializer_list<int> l) { copy(l.begin(),l.end(),x); }
// constructor 2. using a variadic template
template<class ...T> s(T... l) : x{l...} {} ;
// constructor 3. copy from an existing array
s(int* l) { copy(l,l+5,x);}
};
int f(s instance){ return instance.x[2]; }
int main(){
s a1({1,2,3,4,5}); // calls constructor 1 (or 2 if 1 is left out)
s a2{1,2,3,4,5}; // calls constructor 1 (or 2 if 1 is left out)
s b1(1,2,3,4,5); // calls constructor 2
int l[5] = {1,2,3,4,5};
s c1(l); // calls constructor 3
cout << l[2] << endl;
cout << a.x[2] << endl;
cout << f(s(l)) << endl;
cout << f(s{1,2,3,4,5}) << endl; // calls constructor 1 again (or 2 if 1 is left out)
}
关于c++ - c/c++ 函数模板中数组的正确格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19635846/