我正在(重新)学习C++,想初始化一个对象数组。
struct Pea{
Pea(double lower, double upper){
static std::default_random_engine generator;
static std::uniform_real_distribution<double> distribution(lower,upper);
weight = distribution(generator);
}
double weight;
};
class Items{
std::array<Pea,10> peas();
public:
Items(){
}
void show(){
std::for_each(begin(peas),end(peas),
[](auto pea){
std::cout << pea.weight << std::endl;
});
}
};
这个例子是个大傻子,但它只是为了学习。我想初始化一个数组 peas
与随机权重。但我想指定随机的下限和上限。
这一行 std::array<Pea,10> peas(1.2,2.3);
不像预期的那样编译,有谁能建议一种 "现代 "的方法来解决这个问题。
谢谢。
在构造函数中初始化成员,以防需要依赖构造函数参数。
class Items{
std::array<Pea, 3> peas; // no ()
public:
Items() : peas({ {0., 1.}, {2., 3.}, {4., 5.} }) {
}
}
否则,你可以直接初始化它。
class Items{
std::array<Pea, 3> peas{{ {0., 1.}, {2., 3.}, {4., 5.} }};
// ...
}
另一种方法:
class Items{
std::array<Pea, 3> peas = {{ {0., 1.}, {2., 3.}, {4., 5.} }};
// ...
}
这将声明一个名为 peas
归来的 std::array<Pea,10>
那是行不通的。
std::array<Pea,10> peas();
下面是我对需要做的事情的看法。
#include <algorithm>
#include <array>
#include <iostream>
#include <random>
struct Pea{
Pea(double lower, double upper) {
// the prng should be seeded - or else it'll start with the same default
// seed every time. std::random_device is usually good enough, but if you use
// an old version of MinGW, extra care needs to be taken (see other answers
// for that):
static std::default_random_engine generator{std::random_device{}()};
// don't make the distribution static or else all Peas will share the same
// distribution:
std::uniform_real_distribution<double> distribution(lower, upper);
weight = distribution(generator);
}
double weight;
};
class Items{
std::array<Pea, 4> peas;
public:
Items() : // use the member initializer list
peas{{ {0., 1.}, {2., 3.}, {4., 5.}, {6., 7.} }}
{}
void show(){
std::for_each(begin(peas),end(peas),
[](auto pea){
std::cout << pea.weight << std::endl;
});
}
};
int main() {
Items i;
i.show();
}
如果你没有其他用途 Items
构造函数,你可以初始化 peas
直接。
class Items{
std::array<Pea, 4> peas{{ {0., 1.}, {2., 3.}, {4., 5.}, {6., 7.} }};
// ...
};