So I have an array of strings. Here’s an example:
std::string array[] = {"Example", "Example2", "Example3"};
Is there any way I can find the number of elements in an array like the one above. I can’t use this method:
int numberofelements = sizeof(array)/sizeof(array[0]);
This is because the size of the elements vary. Is there another way?
Given your array of strings, you can most certainly use
sizeof(array)/sizeof(array[0])to get its size and the following program works just fine:It is not clear what do you mean by saying that size of elements vary. Size of the elements of any array is always known at compiler-time, no exceptions.
There are, however, situations where the above will not work. Consider the following example:
The above code is doomed to fail. It might look a bit weird at first, but the reason for this is actually very simple — this is called array decaying. It means that every time you pass an array to a function, its type is automatically decayed to that of a pointer. So the above function is in fact an equivalent of this:
And if in the first example the
sizeofoperator returns the total size of an array, in the second example it returns the size of a pointer to that array, which is a totally different thing.There are usually two ways people go about it. The first is to add a special “last” element of the array so that application can traverse the array until it sees the last element and calculate the array’s length. String literals are the perfect example of this — every string literal ends with ‘\0’ and you can always calculate its length. Here is an example:
The downside is obviously a need to traverse the array to determine its length. The second way it to always carry array length around, for example:
In C++, you can use a template to deduct array’s length, for example:
All of the above applies to simple arrays that are built-in into the language. C++, on the other hand, provides a rich set of higher-level containers that give you a lot of flexibility. So you might want to consider using one of the containers that are available to you as part of C++ Standard Library. For a list of standard containers, see — http://en.cppreference.com/w/cpp/container
Hope it helps. Good Luck!