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

相关问题