构造参数列表的更简单的方法是什么

A more simpler way to construct a list of arguments?

本文关键字:更简单 是什么 方法 列表 参数      更新时间:2024-09-26

我正在尝试创建map[per]类型的代码,但我正在寻找一种更简单的构造函数编码方法。

一个例子:


#define B {0, 0, 0, 0, 1}

struct A {
A(int a = 0, int b = 0, int c = 0, int d = 0, int e = 0) {
this->args[0] = a;
this->args[1] = b;
this->args[2] = c;
this->args[3] = d;
this->args[4] = e;
};
~A() {};
int args[5];
};

我所说的更简单的意思是:

#define C { {},{},{},{} } 
struct B {
B(){};
int d,e;
char f,g;
}
struct A {
A(B b[] = {}) { };
B strct[4];
}
A a = C;

我就是不能去上班。

如果我理解正确,您正在尝试找到一种更简单的方法来构建类A:

struct A
{
A(int a = 0, int b = 0, int c = 0, int d = 0, int e = 0)
: args{a, b, c, d, e} {};
~A(){};
int args[5];
};

我们可以使用大括号初始化数组int[5]

您可以使用一个可变模板,比如。。。

struct A {
template <typename... T>
A(T... a) : args{a...} {};
int args[5];
};
int main() {
A a1(1);    // Initializes only the first element individually; others get default initialized (zero-initialized)
A a2(1,2);  // first two elements get initialized individually
// A a6(1,2,3,4,5,6);  // Error: Excess elements in array initializer
}

一个选项(C++11及更高版本(使用initializer_list。例如

#include <initializer_list>
#include <algorithm>
struct A
{
A(std::initializer_list<int> values) : args {0}
{
if (values.size() < 5)
std::copy(values.begin(), values.end(), args);
}
int args[5];
};
int main()
{
A  a{1,2,3};    // note the values are in curly braces
for (int v : a.args) std::cout << v << ' ';
std::cout << 'n';
} 

构造函数的initializer列表中的args{0}args的所有元素初始化为零,循环最多接受initializer表中的五个值。如果提供了五个以上的值,则在上述内容中将忽略所有值。

如果您想使用参数创建一个具有任意数量int的容器,也可以使用标准容器,如vector

#include <initializer_list>
#include <vector>
struct A
{
A(std::initializer_list<int> values) : args(values)
{
}
std::vector<int> args;
};
// same main() as above.

在这种情况下,a.args(即a.args.size()(中的元素数量将与所提供的元素数量相同(除非明确提供,否则没有尾随零(。