Help with Client Function

I am confused as to what exactly a client function is referring to?
Below is the problem I am working with, and the function I wrote based on what I believe it is. Rip me apart, I need to learn :)

1) Consider a bag of integers. Write a client function that computes the sum of the integers in the bag “aBag”.


1
2
3
4
5
6
7
8
int sumNums(const vector<int>& bagVector )
	{
		bagVector = aBag.toVector();
		int sum;
		for( int i = 0; i < bagVector.length(); i++)
        	    sum += bagVector[i];
	}
	 return sum;
1. Initialize sum to 0 in Line 4
 
int sum = 0;


2. What is aBag in Line 3?

3. Why is the return statement in line 8 outside the curly braces of the function?

The instruction is "Write a client function that computes the sum of the integers in the bag "aBag".

I am assuming that std::vector<ing> aBag is being passed as a parameter to your sumNums() function, which means, &bagVector should have the address of aBag (wherever it may be passed from). Or maybe, somewhere else, your instructor may have defined a class or struct named bag? If that is the case, bag should be passed as a parameter, not std::vector.


Anyways, line 3 will cause an error for 2 reasons.
1. In the local function, aBag was never defined. Also, toVector() was never defined.
2. You've marked the parameter as const in the function header, but you are trying to assign another "value" to it and therefore change the const parameter.


[EDIT]
Let's assume that your instructor did define a class Bag. Then this is how you would create the function
1
2
3
4
5
6
7
8
9
10
11
int sumNums( const Bag &aBag )
{
    // Assuming that toVector() is a const member function of Bag
    std::vector<int> bagVector = aBag.toVector()    
    int sum = 0;

    for( auto x : bagVector )
    { sum += x; }

    return sum;
}
Last edited on
@mpark4656: Yes, the instructor told us to assume that toVector and aBag are already defined. aBag is an instance of an ADT Bag class, and toVector() is one of the member functions of this class.
The goal of this particular problem was to practice adding on to the program by writing a client function that would sum the integers in aBag.

I have never seen this syntax before, ( auto x : bagVector ). Is the auto used to generate automatically the variable type for x?

I see the logic mistakes, with my code. Thank you for your help!
> Is the auto used to generate automatically the variable type for x?
Yes. For more information, http://en.cppreference.com/w/cpp/language/auto

> I have never seen this syntax before.
Range-based for loop, http://en.cppreference.com/w/cpp/language/range-for
Topic archived. No new replies allowed.