This use of iterators crashes.

Hello, Well... actually I have a short piece of code I would like that you guys analyze.
I'm using pointers to iterators but certainly I'm doing it wrong

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
#include <iostream>
#include <vector>

using std::string;
using std::cout;
using std::cin;
using std::endl;
using std::vector;

double sum_vec(vector<double>::iterator*, vector<double>::iterator*);

int main() {
	vector<double> vec(3, 10.5);
	vector<double>::iterator start = vec.begin();
	vector<double>::iterator end = vec.end();
	cout << "Sum of doubles is " << sum_vec(&start, &end) << endl;
	return 0;
}

double sum_vec(vector<double>::iterator *start, vector<double>::iterator *end) {
	double sum = 0.0;
	for( ; start != end; ++start) 
		sum += **start;
	return sum;
}


I was hoping someone could tell me where's my mistake because this little program just crashes.

Thanks in advance.
Jose.
You're treating begin and end like they're iterators... and you're doing that properly.

However you have pointers to iterators, so it's wrong.

The easiest solution is to not use pointers:

1
2
3
4
5
6
7
8
9
10
double sum_vec(vector<double>::iterator, vector<double>::iterator);  // no pointers

//...

double sum_vec(vector<double>::iterator start, vector<double>::iterator end) {
	double sum = 0.0;
	for( ; start != end; ++start)   // this is right if you have iterators
		sum += *start;  // only one * to deref an iterator
	return sum;
}



If you want to change it to be pointers to iterators (but I really don't advise it!) you can do it this way:

1
2
3
4
5
6
double sum_vec(vector<double>::iterator* start, vector<double>::iterator* end) {
	double sum = 0.0;
	for( ; *start != *end; ++(*start))  // note the changes here
		sum += **start;
	return sum;
}
for( ; start != end; ++start) //incorrect dereferencing of your pointers - 3 times



((I assume you are doing this for some test purposes - but there is no need to
pass the parameters by pointer anyway))
Hello,

thanks for the replies, I've fixed it now. but you're right, I'm doing it for testing only, and I really need to know how could I fix the line you (guestgulkan) have so adequatly put:

for( ; start != end; ++start) //incorrect dereferencing of your pointers - 3 times

so that I can preserve my original function declaration.. that is:

double sum_vec(vector<double>::iterator*, vector<double>::iterator*);

like that...

Could you please tell me how to correctly dereference in this case ?

Thank you once again,

Jose.
I already answered that in my post.
I must be blind, I apologize !

Thank you very much Disch, I've noticed you've taken the time to carefully reply many of my questions, I must express my most sincere gratitude, You're really helping me to improve my abilities in the C++ programming language.

Thank you Thank you Thank you !

Keep up the fantastic work.

Jose.
Topic archived. No new replies allowed.