ARRAY SIZE HELP

closed account (ivDwAqkS)
Is there a way to know the number of elements that one array have if you just input the elements without setting an array limit? for example I want to global declare an array like this
1
2
3
4
5
6
7
8
9
10
11
int arr[] = {};

int main(){
     int i = 0;
     for(i=0; i <= 1000 ; i++){
          cin >> arr[i];
          if(arr[i]=-1)
               break;
     }
     return 0;
}


something like that and re-use the size of the array i know i could use this for example declare an extra variable and equaling it to i-1 like this:
 
int j=i-1;

but i don't think it would help me if i wanna use it many times.
ANY HELP PLEASE?
Last edited on
closed account (ivDwAqkS)
Come on please, just need some hint D:.
I would use std::vector instead:
1
2
3
4
5
6
7
8
std::vector<int> nums;
int input;
cin >> input;
while (input != -1)
{
    nums.push_back(input);
    cin >> input;
}
(note that this doesn't store the -1)

Alternatively, set an upper bound for the size of your array, and then have another variable to keep track of where the last element is:
1
2
3
4
5
6
7
8
9
int arr[1000];
int size = 0;
for (int i = 0; i < 1000; ++i)
{
    cin >> arr[i];
    if (arr[i] == -1)
        break;
    ++size;
}

closed account (ivDwAqkS)
the reason i wanted to know it because i need to know it is because i wanna input just the elements that i want and use and use array size to create a program with permutations, the if statement was just for breaking the loop. it is not necessary to be there, and i thought there was another way to do it
Last edited on
Topic archived. No new replies allowed.