Iterator Size for C++ STL Array

Viewed 167

I was trying to understanding STL arrays on a surface level and wrote some code. It goes like this -

#include <iostream>
#include <array>
#include <algorithm>

using namespace std;

int main()
{
    const int p = 8;
    array<int, p> arr;

    for(int i=0; i<p; i++) 
        cin >> arr[i];

    array<int, 1>::iterator at, bt; // this line is the main focus

    at = arr.begin();
    bt = arr.end();

    sort(at, bt);

    for(at = arr.begin(); at != arr.end(); at++)
        cout << *at << endl;

    return 0;
}

In the line array<int, 1>::iterator at, bt;, I defined the iterator to be specific to the size of the array with 1 element. Yet it works perfectly for sizes which are not equal to 1 (8 in this case). The sorting and the print for-loop both work fine.

I changed the 1 in the line to something random, like array<int, 183>::iterator at, bt;, and it still works. What's surprising was when I changed the size to a negative number (let's say -90) or 0, it also seems to work perfectly fine.

I initialized variable at with arr.begin(). How is it possible for an iterator of type array<int, 1> be assigned to array<int, 8>.

What could be the reason for this? What is the underlying concept of defining a size for STL Array Iterators?

1 Answers

What could be the reason for this ?

The reason why it may work is that std::array<int, 1>::iterator happened to be the same type as std::array<int, 8>::iterator, or at least one is implicitly convertible to the other.

This isn't specified by the standard, so it is incidental to the standard library implementation that you use. You shouldn't rely on them being the same type nor convertible. The example program isn't guaranteed to be well-formed.

Related