2

I am trying to develop a C++ program. I am facing a problem. I have declared an array of length 100 as int arr[100].

But I have only filled 20 entries in it. Now I want to find the total number of elements in the array, which should be 20. How do I find the number of elements filled in the array?

I have tried

int size= sizeOf(arr)/sizeof(int); 

but this gives me 100. I only want to get the elements which I have allowed the user to enter.

Actually, there is a situation where the number of generated outputs can be any number. So I assigned each value in a separate array as arr[]. Then I want a loop through the length of the array.

How to calculate the total number of outputs I am getting in the array?

3
  • Is this homework? Or can you use an std::vector? Commented Feb 21, 2011 at 14:58
  • Consider using std::vector. Commented Feb 21, 2011 at 14:59
  • 1
    You could increment a counter as you assign values to the array, or if your code allows for it, use std::vector. Commented Feb 21, 2011 at 15:00

3 Answers 3

8

Every time you work with fixed-size arrays for which you want to consider some positions empty and the others filled, you must keep track of the filled element count in a separate variable. Why? Because you always have 100 elements in your array - you created them. Only that you are not using some of them - and only you know that.

This is one of the many reasons why you should use std::vector.

Sign up to request clarification or add additional context in comments.

2 Comments

no, its not an homework.. its just for my practice. I am trying to improve my programming skills and went through this problem. I havent studied anything about vector.. I will try for it also. Thnx..
@user601236: I never said that this was homework. @birryree did, just above.
1

With C/C++ arrays, there is no way to determine this unless you have another variable keeping track.

You might actually be looking for a vector instead.

Comments

1

The features you want can be found in std::vector, and std::deque.

When using C++, it is preferred to use the standard containers over the C-style arrays.

2 Comments

No, std::array doesn't track "used" separately from "capacity".
@BenVoigt You are correct. I've edited to remove the inaccurate portion (though, std::array would still be preferred over a C-style array).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.