I'm just trying to figure out how this stuff works. I wrote this function:

#include <algorithm>
#include <vector>
	double VectorMax(const vector<double> &a)
	{
		vector<double>::iterator pos;
		pos = max_element (a.begin(), a.end());
		return *pos;
	}

and call it with:

vector<double> Numbers;
	Numbers.push_back(3.4);
	Numbers.push_back(4.5);
	Numbers.push_back(1.2);
	
	cout << VectorMax(Numbers) << endl;

but I get "no match for operator=" error. Since this is just a container of doubles, shouldn't = already be defined?

Thanks,
Dave

You should use a const_iterator: vector<double>::const_iterator pos; I'm assuming you have a using namespace std; in your actual code. (Please post runnable code.)

Yep, that did it, thanks. Forgot about the const iterators.
Sorry I forgot to include "using namepace std;"

Dave

I tried to make a template out of this:

template <typename T>
	T VectorMax(const vector<T> &a)
	{
		vector<T>::const_iterator pos;
		pos = max_element (a.begin(), a.end());
		return *pos;
	}

but now I get "error: expected ; before 'pos' "

Declare your iterator like this: typename vector<T>::const_iterator pos;

That worked. Why do you have to do that?

I'm not exactly sure! I've learned to try typename in situations like that.

Obviously it's disambiguating something. It isn't needed if you use a concrete type like int instead of T, so it has something to do with that. Apparently the compiler cannot be sure exactly what a vector<T>::const_iterator is and needs the hint that it is indeed a typename.

Perhaps a C++ guru can tell us more.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.