构造参数列表的更简单的方法是什么
A more simpler way to construct a list of arguments?
我正在尝试创建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()
(中的元素数量将与所提供的元素数量相同(除非明确提供,否则没有尾随零(。
相关文章:
- 当无法使用模板和宏时,生成类型变体C++代码的最简单方法是什么?
- 在OSX上使用CMake将Adobe的XMP工具包构建为共享库的最简单方法是什么?
- 通过比较C++中的行在 txt 文件中搜索的最简单方法是什么?
- 在C++中创建文件夹选取器对话框的最简单方法是什么?
- 存储变量的更有效方法是什么?
- Protobuf中重复字段的问题.使用重复字段进行序列化/反序列化的更好方法是什么?
- 编写按初始值循环的循环的更好方法是什么
- 是什么导致我的循环在第一次迭代中运行得更慢
- 创建可以遍历 std::map 值的通用模板迭代器的最简单方法是什么?
- 标准库容器最简单、性能差的哈希类是什么?
- 初始化类成员的更好做法是什么?
- 在 if 语句中处理多个 or 的更优雅的方法是什么
- 根据浮点符号对浮点进行舍入的最简单方法是什么
- 最简单的事件设计模式是什么
- 删除数组成员的更好方法是什么?
- 而循环比循环更有效.可能是什么原因
- 对于我扩展此程序来计算最高10x10矩阵的倒数的最简单方法是什么
- 在C 中操作数据的更好方法是什么
- C++98 中获取并继续调用当前类不知道的类方法的最简单方法是什么?
- 比较字符串大小写不区分的简单方法是什么?