结构体数组成员的默认值
可能的重复:
在 C++ 类中初始化数组和可修改左值问题< /a>
如 这个问题,可以给一个ctor一个结构体,使其成员获得默认值。如何继续为结构内数组的每个元素赋予默认值。
struct foo
{
int array[ 10 ];
int simpleInt;
foo() : simpleInt(0) {}; // only initialize the int...
}
有没有某种方法可以在一行中实现类似于初始化 int 的方式?
Possible Duplicate:
Intitialzing an array in a C++ class and modifiable lvalue problem
As seen in this question, it's possible to give a ctor to a struct to make it members get default values. How would you proceed to give a default value to every element of an array inside a struct.
struct foo
{
int array[ 10 ];
int simpleInt;
foo() : simpleInt(0) {}; // only initialize the int...
}
Is there some way to make this in one line similar to how you would do to initialize an int?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
新的 C++ 标准有一种方法可以做到这一点:
测试: https://ideone.com/enBUu
如果你的编译器尚不支持此语法,您始终可以分配给数组的每个元素:
编辑:2011 年之前的 C++ 中的单行解决方案需要不同的容器类型,例如 C++ 矢量(无论如何都是首选)或 boost 数组,它们可以是 boost.assign'ed
Thew new C++ standard has a way to do this:
test: https://ideone.com/enBUu
If your compiler does not support this syntax yet, you can always assign to each element of the array:
EDIT: one-liner solutions in pre-2011 C++ require different container types, such as C++ vector (which is preferred anyway) or boost array, which can be boost.assign'ed
将数组更改为 std::vector 将允许您进行简单的初始化,并且您将获得使用向量的其他好处。
Changing the array to a std::vector will allow you to do simple initialization and you'll gain the other benefits of using a vector.
如果你只想默认初始化数组(将内置类型设置为 0),你可以这样做:
If you just want to default-initialize the array (setting built-in types to 0), you can do it like this:
或使用
std::generate(begin, end, Generator);
,其中生成器由您决定。or use
std::generate(begin, end, generator);
where the generator is up to you.