Determining the size of an array needed to store unknown amount of integers

Let's say you have a text file with x amount of numbers stored one by one in seperated text lines, you load them all word by word into a string and then convert them to integers and store in array of integers like this :

1
2
3
4
5
6
7
8
9
ifstream file("blablabla.txt");
string s;
int i = 0;
int array[ ??? ];
while(file>>s){
  istringstream ss(s);
  ss = array[i];
  i++;
}


So the question is - how do you know how wide your array must be ? Until now I just made an array of 10k elements to make sure all the loaded files will not cause any errors(unless there are more than 10000 of numbers in them), but I know it is not the right thing to do, how to determine size of my array ?
This being C++, you can avoid having to deal with it yourself by using a proper C++ container. For example, a vector of int types:

vector<int> array;

and then simply add each int as you read them in using the push_back class function.

http://www.cplusplus.com/reference/stl/vector/
if all the numbers are separated by spaces you can simply read through the file counting how many their are and then allocate it dynamically.

But I would use the STL list to be honest. Vectors are easier but are not as efficient when you are constantly adding to them dynamically.
Last edited on
Thanks guys, I thought about the first option IceThatJaw, to be honest that is how I'm planning to do this for now, but vectors sound more logic though, anyway cheers for the help.
You can make a vector's push_back more efficient be reserving space, if you have a rough idea about how many elements you're expecting.

Another possibility is to use a deque, unless you need the storage to be contiguous. The memory for a deque is allocated in chunks, so the resizing of the array is more efficient.
Last edited on
Topic archived. No new replies allowed.