2009-05-05 28 views
12

使用C++和STL,是否有人知道如何將整數數組存儲爲STL列表或向量中的節點?我需要存儲數量未知的數字對,並且來自其他語言,我首先想到的是使用某種類型的列表或向量數據結構...但我遇到了一些麻煩。我100%肯定自己正在犯一個明顯的初學者的C++錯誤,而那些真正瞭解這門語言的人會看看我想要做的事情,並且能夠讓我直觀。如何將數組存儲在STL列表中?

所以,這是我試過的。聲明一個列表,像這樣的工作:

stl::list<int[2]> my_list; 

,然後我可以很容易地使兩個元素的數組,像這樣:

int foo[2] = {1,2}; 

這編譯和運行就好了。然而,當我嘗試添加foo我的名單,像這樣:

my_list.push_back(foo); 

我得到一個整體粗糙集編譯器錯誤,其中沒有我真的能理解(我的C++的 - 福幾乎是不存在的):

/usr/include/c++/4.0.0/ext/new_allocator.h: In member function ‘void __gnu_cxx::new_allocator<_Tp>::construct(_Tp*, const _Tp&) [with _Tp = int [2]]’: 
/usr/include/c++/4.0.0/bits/stl_list.h:440: instantiated from ‘std::_List_node<_Tp>* std::list<_Tp, _Alloc>::_M_create_node(const _Tp&) [with _Tp = int [2], _Alloc = std::allocator<int [2]>]’ 
/usr/include/c++/4.0.0/bits/stl_list.h:1151: instantiated from ‘void std::list<_Tp, _Alloc>::_M_insert(std::_List_iterator<_Tp>, const _Tp&) [with _Tp = int [2], _Alloc = std::allocator<int [2]>]’ 
/usr/include/c++/4.0.0/bits/stl_list.h:773: instantiated from ‘void std::list<_Tp, _Alloc>::push_back(const _Tp&) [with _Tp = int [2], _Alloc = std::allocator<int [2]>]’ 
test.cpp:5: instantiated from here 
/usr/include/c++/4.0.0/ext/new_allocator.h:104: error: ISO C++ forbids initialization in array new 

那麼,有人有什麼想法,我在做什麼錯在這裏?任何指針(沒有雙關語意圖)將是最有幫助的。是不是可以存儲數組在一個std :: list?我應該使用一個結構?我只是在某處丟失了*&

回答

9

不能將數組存儲在STL容器中。對於一般情況,你會使用矢量或某些矢量。對於您的具體情況,我會使用std :: pair的向量,如下所示:std::vector<std::pair<int, int> >std::pair是一個類,它有兩個成員,firstsecond,無論你想要什麼類型。

編輯:我本來它爲std::vector<std::pair<int> >,但我不知道這是否超載只接受1在這兩種類型都翻起來,沒有證據的這一樣的...小挖的情況下參數,所以我修改它明確指出,firstsecond都是int s。

+1

標準中的定義不提供第二種類型的默認類型,因此您必須明確提供這兩種類型。 – 2009-05-05 22:16:57

23

存儲在標準庫容器中的東西必須是可分配和可複製的 - 數組既不是。你最好的選擇是創建一個std :: vector列表。或者,您可以將數組包裝在結構中:

struct A { 
    int array[2]; 
}; 

std::list <A> alist; 
+0

你會如何推到數組到'alist`? – JFA 2015-03-07 20:16:44

7

這是使用boost::array而不是「經典」C風格陣列的一個很好的情況。 這應該工作:

std::list<boost::array<int,2> > my_list; 
boost::array<int,2> foo={{1,2}}; 
my_list.push_back(foo); 
5

我建議你使用std ::對的值存儲在這種情況下。它位於
<utility>

你可以在列表中存儲指向數組的指針,但是你必須處理所有的內存管理。如果成對的值是你所需要的,使用pair就簡單多了。

1

由於C++ 11中,我們可以使用標準std::array做到這一點:

#include <array> 
#include <list> 
#include <iostream> 

int main() { 
    std::list<std::array<int, 2>> l {{3,4},{5,6}}; 
    l.push_back({1,2}); 

    for (const auto &arr : l) 
     for (const auto &v : arr) 
      std::cout << v << ' '; 
} 

l.push_back({{1,2}}); 

等沉默一些鐺警告。

輸出:

3 4 5 6 1 2 
1

用C++ 11有可用的::std::array wrapper可與標準集裝箱像這樣使用:

#include <array> 
#include <iostream> 
#include <list> 
#include <cstdint> 

int 
main() 
{ 
    using t_Buffer = ::std::array<::std::int32_t, 2>; 
    using t_Buffers = ::std::list<t_Buffer>; 
    t_Buffers buffers; 
    buffers.emplace_back(t_Buffer{1, 2}); 
    ::std::cout << buffers.front()[0] << " " << buffers.front()[1] << ::std::endl; 
    return(0); 
} 

Run this code online