The general syntax of declaring an array container is: array<object_type, size> array_name; The above declaration creates an array container 'array_name' with size 'size' and with objects of type 'object_type'.
The array class is a template class found in the STL. It is considered as one of the STL container classes so it has many of the same features as other STL containers such as the vector class.
C++ allows us a facility to create an array of lists. An array of lists is an array in which each element is a list on its own. Syntax: list<dataType> myContainer[N];
Vector may have a default size. List does not have default size. In vector, each element only requires the space for itself only. In list, each element requires extra space for the node which holds the element, including pointers to the next and previous elements in the list.
Using C++ and the STL, does anybody know how to store integer arrays as nodes in an STL list or vector? I have an unknown number of pairs of numbers that I need to store, and coming from other languages my first thought was to use some sort of list- or vector-like data structure... but I'm running into some trouble. I am 100% sure that I'm making an obvious beginner's C++ mistake, and that somebody who actually knows the language will take one look at what I'm trying to do and be able to set me straight.
So, here's what I've tried. Declaring a list like so works:
stl::list<int[2]> my_list;
And then I can easily make a two-element array, like so:
int foo[2] = {1,2};
This compiles and runs just fine. However, as soon as I try to add foo
to my list, like so:
my_list.push_back(foo);
I get a whole gnarly set of compiler errors, none of which I really understand (my C++-fu is almost non-existent):
/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
So, anybody have ideas as to what I'm doing wrong here? Any pointers (no pun intended) would be most helpful. Is it just not possible to store arrays in a std::list? Should I be using a struct? Am I just missing a *
or &
somewhere?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With