PDA

View Full Version : silly array element counter..



ct
1st March 2006, 21: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[])
{
//code

}

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..

wysota
1st March 2006, 21: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.

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

See "What's wrong with arrays?" at
http://public.research.att.com/~bs/bs_faq2.html

dublet
3rd March 2006, 11: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. ;)

Ben.Hines
3rd March 2006, 16: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.
}
}