Is there a way to have an array with an undeclared size? It would automatically put the data into the appropriate subscript without delaring the subscript each time. So something like this

int Array[]

Array + 1,
Array + 1,
Array + 1,

<<array; (equals 3 )

Instead of something like this,

int Array(3)
Array(0) + 1
Array(1) + 1
Array(2) + 1

Array(1) + Array (2) etc etc..

So it's like a simple standard variable declaration except each time it is written to, the written data is stored like an array, instead of being overwritten each time like a standard variable. The normal way of declaring an array is also bulky. It takes as much time / effort to interact with than a set of ordinary variables. Rather self defeating...Also, it's better that the array creates only the subscripts on a need to do basis, so one would'nt have a bunch of empty wasted array space beacause the array(10000) could'nt all be filled.

Sorry if this is vague.

8 Years
Discussion Span
Last Post by Narue

What you asked for, by my reading, is an array that grows automatically to fit whatever index you provide. So if you say int array[], then try to index array[100], the array will resize itself to have 101 elements.

You can do this with dynamic arrays and such things as the std::vector class, but managing the size is still somewhat manual. You can wrap it in a class though, and abstract the work away into a nice convenient syntax (expand to suit your tastes and standard container rules):

#include <iostream>
#include <vector>

template <typename T>
class auto_vector {
  std::vector<T> _base;
  typedef typename std::vector<T>::size_type size_type;
  auto_vector() {}
  auto_vector ( const std::vector<T>& init )
    : _Base ( init )

  size_type size() const { return _base.size(); }

  T& operator[] ( size_type i )
    if ( _base.size() < i )
      _base.resize ( i + 1 );

    return _base[i];

int main()
  auto_vector<int> v;

  v[10] = 12345;

  for ( auto_vector<int>::size_type i = 0; i < v.size(); i++ )
    std::cout<< v[i] <<'\n';

Other languages have tried this with their built-in array type, and it's generally accepted to be a bad idea because indexing bugs can remain hidden often with no more of a symptom than wasted memory.

Votes + Comments
Nice STL extend and then pointing out why it is such a bad idea !!
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.