Having Problem With a Vector Function.

I'm having a problem with the sumVector function part of this program.the loop to sum and the way to call the function The description on what to do is as follows
The sumVector function will not take any input parameters. It will contain a loop
that asks the user for an integer to add to the vector (the vector begins empty).
It will continue until the user types 0. The function will then loop through all items in the vector, sum them, and return that sum. Id appreciate any help

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76

#include<iostream>
#include<vector>
using namespace std;
int sumArray(int[], int);
int sumVector(vector<int>); // function prototype


int main()
{
	const int ARRAY_SIZE = 10;
	int numbers[ARRAY_SIZE];
	vector<int> values; // vector to hold values

	int count = 0;
	int num;
	int value;

	cout << "enter a number or -1 to quit \n";
	cin >> num;
	while (num != -1 && count < ARRAY_SIZE)
	{

		numbers[count] = num;
		count++;
		cout << "enter a number or -1 to quit \n";
		cin >> num;
	}

	int sum = sumArray(numbers, count);
	cout << "\nThe sum is: " << sum << '\n';

	//calling vector
	value = 0;
	cout << " enter a number or 0 to quit \n";
	cin >> value;

	while (value != 0)
	{
		numbers[count] = value;
		count++;
		cout << "enter a number or 0 to quit \n";
		cin >> value;
	}

	int value = sumVector();
	cout << "\nThe sum is: " << value << '\n';

	system("pause");
	return 0;
}
int sumArray(int arr[], int num_entries)
{
	int sum = 0;

	for (int i = 0; i < num_entries; i++)
	{
		sum += arr[i];
	}

	return sum;
}

int sumVector(int [], int num_entries)
{
	int sum = 0;

	for (int i = 0; i < num_entries; i++)
	{
		sum += [i];
	}

	return sum;
}

 
Last edited on
At line 6 you declare:
int sumVector(vector<int>);

At line 46 you attempt to call:
int value = sumVector();
But you haven't declared any function called sumVector that takes no parameters.

At line 64 you define:
int sumVector(int [], int num_entries)

This function is different from the other two.

So there are 3 different function called sumVector here. If you want to use one, you have the declare it, call it, and define it the same way.
1
2
3
int sumVector(vector<int>); //declaration
int value = sumVector(); //call
int sumVector(int [], int num_entries) //definition 
lets say that you want to move a piano from your grandma's house to the local theatre.
you hire Valentino and he ask you to provide the truck, no problem
the day of the moving you give him no truck. Also, Valentino only knowns how to ride motorcycles.
¿do you realise that there's a problem?


now, ¿what about all that code were you use an array?
you did manage that time, ¿why are you choking now?
Hello arg57,


1.) The sumVector function will not take any input parameters.

2.) It will contain a loop that asks the user for an integer to add to the vector (the vector begins empty).

3.) It will continue until the user types 0. The function will then loop through all items in the vector, sum them, and return that sum.


See any problem here?
1
2
3
4
5
6
7
8
9
10
11
int sumVector(int [], int num_entries)
{
	int sum = 0;

	for (int i = 0; i < num_entries; i++)
	{
		sum += [i];
	}

	return sum;
}


Although int [] is sufficient for a prototype it is missing the variable name for a function definition. This is just a note because you have totally misinterpreted step 1. As for steps 2 and 3 they do not even exist.

Looking over the rest of the program the prototype for "sumVector" does not match the function definition and both are wrong since it should be int sumVector().

In main" what is the array for? I get the idea that this is about vectors not arrays.

On line 17 you define "value" then on line 46 you try to redefine "value" again. this will not work. I believe what you intended here is value = sumVector();. At least you got the function call correct.

I am not sure what your idea is for the first while loop? The second while loop is better put in the function "sumVector()"

You could do away with the variable "value" and write the "cout" statement on line 47 as: cout << "\nThe sum is: " << sumVector() << '\n'; since the function returns a value that can be used in the "cout" statement.

I will load this up and see what else I can come up with.

Hope that helps,

Andy
the array function was the first part of the program which I might be getting confused by so I separated them to maybe make it easier still have trouble with the for loop just brain dead
#include<iostream>
#include <vector>
int sumVector(vector<int>);//prototype
using namespace std;

int main()

{
vector<int> value;

//int values;
cout << " enter a number or 0 to quit \n";
cin >> value;

while (value != 0)
{
cout << "enter a number or 0 to quit \n";
cin >> value;
count++;
}

int sumVector(); //call
cout << "\nThe sum is: " << sumVector() << '\n';

system("pause");
return 0;
}
sum = 0;
int sumVector(int[], int num_entries) //definition
for (count = 0; count < sumVector(); count++)
{
sum += sumVector();
}
Hello arg57,


1.) The sumVector function will not take any input parameters.

2.) It will contain a loop that asks the user for an integer to add to the vector (the vector begins empty).

3.) It will continue until the user types 0. The function will then loop through all items in the vector, sum them, and return that sum.


These are the instructions that you provided. What part do you not understand??

You must be brain dead because you forgot what code tags are for.

dhayden Wrote:
So there are 3 different function called sumVector here. If you want to use one, you have the declare it, call it, and define it the same way.


I think it is time to scrap what you have and start over. Forget about the arrays and concentrate on the vector. Read and understand your instructions before you get started.

The program is not that difficult. There is not much to do in "main" and most of the work is done in the function.

Hope that helps,

Andy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>
#include <vector>

int sumVector(std::vector<int>&);

int main()
{
   std::vector<int> values; // creates an empty vector

   int num;

   std::cout << "Enter a number or -1 to quit \n";

   while (true)
   {
      std::cin >> num;

      if (num == -1)
      {
         break;
      }

      values.push_back(num);  // adding the input value to the vector
   }

   std::cout << "\nThe vector holds " << values.size() << " values.\n\n";

   int value = sumVector(values);
   
   std::cout << "The sum is: " << value << '\n';
}

int sumVector(std::vector<int>& vec)
{
   int sum = 0;

   for (auto itr = vec.cbegin(); itr != vec.cend(); itr++)
   {
      sum += *itr;
   }

   return sum;
}
Enter a number or -1 to quit
1
2
3
4
5
6
7
8
9
10
-1

The vector holds 10 values.

The sum is: 55
Enter a number or -1 to quit
5
10
15
20
-1

The vector holds 4 values.

The sum is: 50

A std::vector is a complex data type, passing a vector by reference prevents a needless copy being made. Passing by value can be a performance hit.

The loop summing the values of the passed vector looks a bit strange. It is using iterators to make it harder to access outside the vector boundaries.
std::vector can be sized when creating one, same as a C array, with slight differences of syntax. If you create a sized array then you can access individual elements using operator[].
With changes to main you can ask the user how many numbers they want to enter (the rest of the code is unchanged):
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
int main()
{
   std::cout << "How many numbers do you want to enter? ";
   int num;
   std::cin >> num;

   std::vector<int> values(num); // create a sized vector, default filled with zeroes

   std::cout << "Enter a number or -1 to quit \n";

   int value;
   
   for (int i = 0; i < num; i++)
   {
      std::cin >> value;

      if (value == -1)
      {
         break;
      }

      values[i] = value;  // adding the input value to the vector
   }

   std::cout << "\nThe vector holds " << values.size() << " values.\n\n";

   value = sumVector(values);
   
   std::cout << "The sum is: " << value << '\n';
}
How many numbers do you want to enter? 5
Enter a number or -1 to quit
1
2
3
4
5

The vector holds 5 values.

The sum is: 15
How many numbers do you want to enter? 5
Enter a number or -1 to quit
5
10
15
-1

The vector holds 5 values.

The sum is: 30
Thanks Furry Guy and everybody else. Appreciate all your help
int sumVector(std::vector<int>& vec)
if you do not intend to modify the vector, pass it by constant reference

> It is using iterators to make it harder to access outside the vector boundaries.
I fail to see how that's less error-prone
a range loop may be better for(const auto &x: vec)

> std::cout << "How many numbers do you want to enter? ";
> std::cout << "Enter a number or -1 to quit \n";
¿which one? now your vector has n element, but you inputted less than that


> You must be brain dead because you forgot what code tags are for.
calm down, the interface doesn't work well
if you do not intend to modify the vector, pass it by constant reference

One step at a time, in small chunks, to help make eating the whole std::vector cow easier to consume.

If you had noticed the for loop you complained about used constant iterators cbegin() and cend().

The OP is still learning, and making small not perfect changes to existing code helps the learning process. Later exposure to better methods so they are not overwhelmed by TMI.

Every comment/complaint you raise is something I thought about while designing the examples and decided against for small changes clarity.

¿which one? now your vector has n element, but you inputted less than that

A deliberate design choice, to help the OP grasp that there is more than one way to instantiate a vector. And what the implications of using the size-on-creation method can have when not completely over-writing all of the elements.

Last edited on
ok, don't know what's better for teaching. (however, would say that giving him the solution the last time didn't do too good, but again, can't say what will change)

¿what's TMI?
Last edited on
TMI = Too Much Information.

The OP started out in another thread wanting to sum the elements in a C array, using a function. I provided some code there.

http://www.cplusplus.com/forum/beginner/252098/

Apparently he copy 'n' pasted the sample code I gave him there and layered on std::vector code for his code in this thread.

I saw immediately where he went wrong, and where he was going in the right direction. I deliberately created a couple of examples that pointed out two ways of doing things when dealing with std::vector, with "easy to notice" minimal changes.

Was it the best way to work with std:vector? No, but it was an introduction for what appears to be someone learning a new C++ concept.

I didn't want to scare him off by throwing too much "this is THE BEST WAY to do things" information at him right away. He can still learn more mature methods for using std::vector, hopefully eager to learn more. Either on his own, or here with code and questions.

You have a different teaching style from mine. I certainly wouldn't complain about your technique.

I prefer taking small steps that lead toward the big things, maybe inspiring questions along the way.
Hi I'm taking a online course from a Comm. college and all I have is a book and a useless teacher. first time I saw arrays or vectors was a week ago. Some of this is beyond the scope of my book so far its just a beginners course C++ 01. take the for loop never saw those commands before not sure what they do Im used to For (I =0; I < num; ++I) so this is the assignment I got haven't heard from the teach for 2 weeks he doesn't explain anything so I'm pretty much on my own. Didn't mean to start an argument I just looking for help Thanks again
this site has a massive language reference inside and those have tutorials in them.

so if you clicked reference, tutorials, … you would find stuff as good or better than many text books : http://www.cplusplus.com/doc/tutorial/ complete with example code snips that show the concepts (usually very well done).

for loops are under "control structures". Many colleges are not yet onboard with teaching the newer language features (stuff added in 2011 and 2017) which includes the cool for loops.

For reference: my first class started from 0 knowledge and covered arrays, sorting algorithms, linked lists and trees, binary search … a 'beginner' course can have quite a lot in it..
Last edited on
One slight problem IMO with the reference and tutorial sections here at cplusplus is updating effectively ceased sometime after the C++14 standard was released. No C++17 material.

cppreference is updated quite frequently, but the explanations and code samples are more technically oriented. Up-to-date with C++17 along with some C++20 bits that have been tentatively approved for inclusion in the next standard. Not a resource I'd recommend for learning the language basics, though.

Another beginner tutorial resource, one that is updated:

http://www.learncpp.com/

Didn't mean to start an argument I just looking for help

Just a difference of opinion from people who do want to help. :)
Thanks a lot Glad I found this site Looks like a lot of info and tutorials and help .
closed account (z05DSL3A)
I saw in another thread that Handy Andy was being...uncharacteristic.

I think he was the only one that pointed out what the OP was being asked to do did not match the code that was being fixed...I don't blame him for being uncharacteristic.
Topic archived. No new replies allowed.