2013-02-14 37 views
0

在我的代碼我有一個向量:錯誤創建從stl_vector.h結構(可能是微不足道的)

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

'0'不是'datapoint'類型的有效值。 – us2012 2013-02-14 19:54:37

+0

你在這裏做什麼'std :: vector spectrum(71,0);'? – juanchopanza 2013-02-14 20:02:47

回答

3

您正在嘗試調用的vector填充構造函數:

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

0datapoint類型的有效價值。

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

then std :: vector spectrum(71);

玩得開心,

+1

用C++ 11很好,對於定義構造函數的舊版本要小心,這意味着類型不再是POD - 代碼的其他部分可能依賴於此。有關詳細信息,請參閱http://stackoverflow.com/questions/6496545/trivial-vs-standard-layout-vs-pod。 – us2012 2013-02-14 20:16:19

+0

其他部分如何回覆?這不應該是他們考慮簡單的舊數據風格的錯誤嗎? – blackmath 2013-02-14 20:23:24

+0

這是什麼樣的論點?假設你正在與一個大系統,外部圖書館等合作 - 你不可能完全像「我會改變這一點,我不在乎它是否因爲其他人的錯誤而失敗,因爲這是其他人的錯。首先」。 – us2012 2013-02-14 20:26:56