View Full Version : silly array element counter..

1st March 2006, 20:08
Ok.. first of all I am a bit new to STL, however I am having this problem in C++.

I have got a function defined as

int MyClass::MyString(string str[])


Is there any way to find out how many elements of array are being passed to the function.
I have no way to know how many functions are being passed but only know that the constratints would be say 1 to 100 as I don't have the code that calls the function and am only supposed to write this single class.

doing (sizeof(str)/sizeof(str[0])) returns "1" and is of no use..

is there some way to find count the elements of this string array..

1st March 2006, 20:16
No, there is no way. But you can use a std::vector instead of an array. This way you'll be able to retrieve the number of object it contains.

1st March 2006, 22:16
Stroustrup recommends not using arrays. Many coding standards insist on never using arrays.

See "What's wrong with arrays?" at

3rd March 2006, 10:21
Unless your array is NULL terminated, you have no way of finding out. This is why you often see array length as argument to array functions. ;)

3rd March 2006, 15:50
It may be nice to not impose a particular type of container (like std::vector) on the callers of the int MyClass::MyString method. Sometimes, I like to make these types of methods templatized on an iterator type like this:

template< class IteratorType >
int MyClass::MyString(const IteratorType &iterBegin, const IteratorType &iterEnd)
// Get a count of items passed in.
const size_t nNumItems = iterEnd-iterBegin;

// Iterate over the input
IteratorType iter;
for(iter = iterBegin; iter != iterEnd; ++iter)
// Do something here.