tags:

views:

64

answers:

3
#include<iostream>
#include<string> 


using namespace std;

class Prerequisites
{
    public:
    void orderClasses(string* Input);
};


void Prerequisites::orderClasses(string* Input)
{
        // Need to find the length of the array Input

}

int main()
{

    Prerequisites A;

    string classes[]={"CSE121: CSE110",
        "CSE110:",
        "MATH122:"
         };


    A.orderClasses(classes);

}

I need to find the length of the array classes[] in the methos orderClasses. I cannot alter the signature of the method orderClasses ! That is a requirement.

+2  A: 

You should pass the number of elements in the array to orderClasses(). Since that is not an option, consider some alternatives:

  • Add another member function to Prerequisites to inform it how large the array will be when you do call orderClasses().
  • Use a sentinel value for the last string in the array so that when you see that value in the function, you know you have reached the end.
  • Make the first string in the array a string containing the number of elements in the array.

None of these are good solutions to the problem: the best option while still using an array, of course, is just to pass the array size to the function. In most scenarios, it would be even better not to use an array at all and just pass a std::vector<std::string> containing the strings.

James McNellis
I am not sure , if I can change the Input or the method. But adding the the member function seems cool though!!
Eternal Learner
A: 

The information is just not there. Can't you add a last item to the classes[] array that's a "well-known end-marker/sentinel"? That meets the requirement of not changing the method signature (you're just changing the data passed to it, not the signature;-).

Alex Martelli
A: 

I never heard that in c++ people are using arrays when there is a far more powerful STL tools.

prabhakaran