My homework assignment is to write a generic function (using templates) that would find the maximum in a vector. Then I have to test it with ints, longs, and strings. The use of templates mixed with the use of vectors is confusing me. Here is my code so far: (I'm only testing it with integers so far because I'm trying to figure out the maximum function part)

#include <iostream>

#include <vector>

using namespace std;template<typename T>

void maximum(T tVector)

{

T result;

for(int i =0; i+1<3; i++)

{

if(tVector[i]>= tVector[i+1])

result = tVector[i];

}

cout << (result);

}int main()

{

int size = 3;

vector<int> tVector(size);

for(int i =0; i<size; i++)

tVector[i] = (i+1);

cout << tVector[0] << endl;

cout << tVector[1] << endl;

cout << tVector[2] << endl;

maximum(tVector);

cout << tVector.max_size();

}I get errors on these two lines:

result = tVector[i];

error 1: error C2679: binary '=' : no operator found which takes a right-hand operand of type 'int' (or there is no acceptable conversion)

cout << (result);

error 2: error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'std::vector<_Ty>' (or there is no acceptable conversion)

Any ideas?

Your errors are because you are trying to assign a scalar (int) to a variable of type T, which is a vector, and a similar error with cout. You will have to rethink your logic a little.

To expand a bit on what ijackis saying, replace the "T" in your function with the type of the variable you're passing, and you end up with this. Once you do, it's easy to see why the complier is complaining.void maximum(vector<int> tVector) { vector<int> result; for(int i =0; i+1<3; i++) { if(tVector[i]>= tVector[i+1]) result = tVector[i]; } cout << (result); }

Ask Your Question

Weekly Poll