std::list construction


Can somebody please explain the logic of this list construction or at least provide some advice on myt assumptions.

const int a[] = { 5, 2, 6, 1, 13, 9, 19 };
const int count = sizeof(a) / sizeof(a[0]);
std::list<int> l(a, a+ count);

The list is being constructed based on the address of the array which is the first element, to the last element which is calculated based on the first elements address incremented on by the size of the array.

This code works because arrays are stored in a contiguous fashion in C++? allowing us to use pointer arithmetic (beginning address plus total values should give us the end)?

If this is true then the list construction calls what constructor i.e. what are the paramater types?

Thanks in advance
The code works because a pointer to an element of a C-style array is an iterator. This uses the constructor of std::list that takes two InputIterators.
Hi Jeo,

It will call the following constructor:
list (InputIterator first, InputIterator last, const allocator_type& alloc = allocator_type());

Please have look for more info:

Last edited on
Thanks for your reply guys!

I just wanted some clarity on this. If the c style array can be treated as an iterator then how would I store this as an iterator for example:

const int a[] = { 5, 2, 6, 1, 13, 9, 19 };
const int count = sizeof(a) / sizeof(a[0]);
std::list<int>::iterator iter = &a;

I tried taking the address of the array by placing an & in front of it but it un-surprisingly doesn't compile.

Please can you give me an example of how I would do this to allow me to further understand this?

Thanks again.
It's not a list iterator, it's a C array iterator, and its type is const int*

Yep it is const your right and this next one I’m afraid is basic as I never use arrays (normally vectors).

Please can you explain why it is a const int*.

const int* a[];

To me * implies pointer but that is never mentioned in the syntax of the array declaration const int a[]

Thanks and sorry for the basicness of this question.
given an array a, the line const int* p = a; is compiled as const int* p = & a[0]; or, equivalently, const int* p = std::begin(a) ;
When you're using a C array as an argument to a function or operator that expects a pointer parameter and does not expect an array, the compiler constructs a temporary pointer to its first element (which is also its begin iterator)
Last edited on
Ok that makes sense.

Thanks for all of your help it is very useful.
Topic archived. No new replies allowed.