如何将数组存储在STL列表中?

Ste*_*ick 12 c++ arrays stl

使用C++和STL,是否有人知道如何将整数数组存储为STL列表或向量中的节点?我需要存储未知数量的数字对,并且来自其他语言我首先想到的是使用某种类似列表或矢量的数据结构......但我遇到了一些麻烦.我100%肯定我犯了一个明显的初学者的C++错误,并且真正了解这种语言的人会看一眼我正在尝试做的事情并能够让我直截了当.

所以,这就是我尝试过的.声明这样的列表有效:

stl::list<int[2]> my_list;
Run Code Online (Sandbox Code Playgroud)

然后我可以很容易地制作一个双元素数组,如下所示:

int foo[2] = {1,2};
Run Code Online (Sandbox Code Playgroud)

这编译并运行得很好.但是,只要我尝试添加foo到我的列表中,就像这样:

my_list.push_back(foo);
Run Code Online (Sandbox Code Playgroud)

我得到了一整套编译器错误,其中没有一个我真正理解(我的C++ - fu几乎不存在):

/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
Run Code Online (Sandbox Code Playgroud)

所以,任何人都有关于我在这里做错了什么的想法?任何指针(没有双关语)都是最有帮助的.是不是可以将数组存储在std :: list中?我应该使用结构吗?我只是缺少一个*&地方?

小智 24

存储在标准库容器中的东西必须是可分配和可复制的 - 数组都不是.最好的办法是创建一个std :: vector列表.或者,您可以将数组包装在结构中:

struct A {
   int array[2];
};

std::list <A> alist;
Run Code Online (Sandbox Code Playgroud)


rme*_*dor 9

您不能将数组存储在STL容器中.你会使用矢量矢量或一般情况下的一些.对于你的具体情况,我会使用std :: pair的向量,如下所示:std::vector<std::pair<int, int> >. std::pair是有两个成员,一类firstsecond,任何类型的你模板化它是的.

编辑:我最初有它std::vector<std::pair<int> >,但我不确定是否重载只接受1个参数在两种类型都相同的情况下...一点点挖掘没有证据,所以我修改为明确规定,这两个firstsecondint秒.


tim*_*day 7

这是使用boost :: array而不是"经典"C风格数组的好情况.这应该工作:

std::list<boost::array<int,2> > my_list;
boost::array<int,2> foo={{1,2}};
my_list.push_back(foo);
Run Code Online (Sandbox Code Playgroud)


Sam*_*ter 5

我建议你使用std :: pair来存储这种情况下的值.它位于
<utility>.

您可以在列表中存储指向数组的指针,但是您必须处理所有内存管理.如果你需要成对的值,使用pair会简单得多.