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, an
As of C++11, we can do this with the standard 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 << ' ';
}
or
l.push_back({{1,2}});
etc. to silence some clang warning.
Output:
3 4 5 6 1 2
With C++11 there is a ::std::array wrapper available which can be used with standard containers like this:
#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
You can't store arrays in STL containers. You'd use a vector of vectors or somesuch for the general case. For your specific case, I'd use a vector of std::pair, like so: std::vector<std::pair<int, int> >
. std::pair
is a class that has two members, first
and second
, of whatever type you templatize it to be.
Edit: I originally had it as std::vector<std::pair<int> >
, but I wasn't sure if it was overloaded to accept only 1 parameter in the case that both types are the same... a little digging turned up no evidence of this, so I modified it to explicitly state that both first
and second
are int
s.
I'd suggest you use std::pair to store the values in this case. It is located in
<utility>
.
You could store pointers to the arrays in the list but then you would have to deal with all the memory management. Using pair is a lot simpler if pairs of values are all you need.
The thing stored in a Standard Library container must be assignable and copyable - arrays are neither. Your best bet is to create a list of std::vector. Alternatively, you can wrap the array in a struct:
struct A {
int array[2];
};
std::list <A> alist;
This is a good situation for using boost::array instead of "classic" C-style arrays. This should work:
std::list<boost::array<int,2> > my_list;
boost::array<int,2> foo={{1,2}};
my_list.push_back(foo);