我有一个类,其成员是向量的向量:
class binary_image_field_2d {
public:
typedef double field_value_t;
typedef vector<field_value_t> field_t;
protected:
size_t _ndots;
size_t _nfields;
vector<field_t> _fields;
}
我的意思是要拥有一个构造器,该构造器可以使用不同的常量值就地初始化 每个(内部)向量:
binary_image_field_2d(const size_t ndots, const size_t nfields, const vector<field_value_t> init_vals) :
_ndots(ndots), _nfields(nfields),
_fields( initialize here each element of _fields with a vector of
constant value given by an element of init_vals ) {};
例如,如果ndots=3
,nfields=2
和init_vals={0.1, 1.0}
,则用
binary_image_field_2d img;
我的意思是
{{0.1, 0.1, 0.1}, {1.0, 1.0, 1.0}}
该怎么写(如果可能的话)?
答案 0 :(得分:1)
您可以在构造函数中使用私有函数来实现它:
#include <vector>
#include <iostream>
#include <cstdint>
class binary_image_field_2d
{
public:
typedef double field_value_t;
typedef std::vector<field_value_t> field_t;
binary_image_field_2d(const size_t ndots, const size_t nfields, const std::vector<field_value_t> init_vals) : _ndots(ndots), _nfields(nfields),_fields(init_fields(ndots, nfields, init_vals))
{// Empty constructor}
protected:
size_t _ndots;
size_t _nfields;
std::vector<field_t> _fields;
private:
std::vector<field_t> init_fields(const size_t ndots, const size_t nfields, const std::vector<field_value_t> init_vals)
{
std::vector<field_t> vec;
for (int i = 0; i < nfields; ++i)
{
vec.emplace_back(std::vector(ndots, init_vals[i]));
}
return vec;
}
public:
void print_fields()
{
for (auto vec : _fields)
{
for (auto value : vec)
{
std::cout << value << " ";
}
std::cout << std::endl;
}
}
};
int main(void)
{
binary_image_field_2d b(3, 2, {0.1f, 1.1f});
}
您也可以使用lambda函数而不是私有函数来实现它:
#include <vector>
#include <iostream>
#include <cstdint>
class binary_image_field_2d
{
public:
typedef double field_value_t;
typedef std::vector<field_value_t> field_t;
binary_image_field_2d(const size_t ndots, const size_t nfields, const std::vector<field_value_t> init_vals) : _ndots(ndots), _nfields(nfields),
_fields([init_vals, nfields, ndots]() -> std::vector<field_t> {
std::vector<field_t> vec;
for (int i = 0; i < nfields; ++i)
{
vec.emplace_back(std::vector(ndots, init_vals[i]));
}
return vec;
}())
{// Empty constructor}
void print_fields()
{
for (auto vec : _fields)
{
for (auto value : vec)
{
std::cout << value << " ";
}
std::cout << std::endl;
}
}
protected:
size_t _ndots;
size_t _nfields;
std::vector<field_t> _fields;
};
int main(void)
{
binary_image_field_2d b(3, 2, {0.1f, 1.1f});
b.print_fields();
}
在两种情况下,program_output将为:
0.1 0.1 0.1
1.1 1.1 1.1