【问题标题】:error creating a vector of structs from stl_vector.h (probably trivial)从 stl_vector.h 创建结构向量时出错(可能微不足道)
【发布时间】:2013-02-14 19:52:33
【问题描述】:

在我的代码中:

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&)â

我有点困惑,因为我以前这样做过。

【问题讨论】:

  • 0 不是datapoint 类型的有效值。
  • 你想在这里做什么std::vector&lt;datapoint&gt; spectrum(71,0);

标签: c++ vector struct


【解决方案1】:

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

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

0 不是datapoint 类型的有效值。

【讨论】:

    【解决方案2】:
    struct datapoint
    {
        double energy;
        double probability;
        datapoint():energy(0.0), probability (0.0)
        {}
    };
    

    那么 std::向量谱(71);

    玩得开心,

    【讨论】:

    • 对 C++11 很好,注意旧版本,其中定义构造函数意味着类型不再是 POD - 代码的其他部分可能依赖于此。详情请见stackoverflow.com/questions/6496545/…
    • 其他部分怎么回复?考虑简单的旧数据样式不应该是他们的错误吗?
    • 这是什么论据?假设你正在使用一个大系统、外部库等——你不能完全像“我要改变它,我不在乎它是否坏了,因为没有用其他方式做是其他人的错首先”。
    猜你喜欢
    • 1970-01-01
    • 2017-01-30
    • 1970-01-01
    • 2021-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    相关资源
    最近更新 更多