从stl_vector.h创建结构向量时出错(可能是微不足道的)

时间:2013-02-14 19:52:34

标签: c++ vector struct

在我的代码中,我有:

struct datapoint
{
  double energy;
  double probability;
};

后来将其放入这样的矢量中:

std::vector<datapoint> spectrum(71,0);

spectrum[0].energy = 0.937729;
spectrum[0].probability = 0.0022582628449311468;
spectrum[1].energy = 1.875458;
spectrum[1].probability = 0.0033531784328108922;
...

但是,在编译时,对于行

std::vector<datapoint> spectrum(71,0);

我收到错误

/usr/lib/gcc/x86_64-redhat-linux/4.4.6/../../../../include/c++/4.4.6/bits/stl_vector.h: In member function âvoid std::vector<_Tp, _Alloc>::_M_initialize_dispatch(_Integer, _Integer, std::__true_type) [with _Integer = int, _Tp = datapoint, _Alloc = std::allocator<datapoint>]â:
/usr/lib/gcc/x86_64-redhat-linux/4.4.6/../../../../include/c++/4.4.6/bits/stl_vector.h:303:   instantiated from âstd::vector<_Tp, _Alloc>::vector(_InputIterator, _InputIterator, const _Alloc&) [with _InputIterator = int, _Tp = datapoint, _Alloc = std::allocator<datapoint>]â
/src/PrimaryGeneratorAction.cc:74:   instantiated from here
/usr/lib/gcc/x86_64-redhat-linux/4.4.6/../../../../include/c++/4.4.6/bits/stl_vector.h:991: error: no matching function for call to âstd::vector<datapoint, std::allocator<datapoint> >::_M_fill_initialize(size_t, int&)â

我之前有点困惑。

2 个答案:

答案 0 :(得分:3)

您正在尝试调用vector的填充构造函数:

explicit vector (size_type n, const value_type& val = value_type(),
                 const allocator_type& alloc = allocator_type());

0不是类型datapoint的有效值。

答案 1 :(得分:1)

struct datapoint
{
    double energy;
    double probability;
    datapoint():energy(0.0), probability (0.0)
    {}
};

然后     std :: vector spectrum(71);

玩得开心,