Solved C++ Maximum in Vector

April 4, 2012 at 21:02:31
Specs: Windows 7
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?


See More: C++ Maximum in Vector

Report •


#1
April 4, 2012 at 23:36:57
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.

Report •

#2
April 5, 2012 at 04:19:53
✔ Best Answer
To expand a bit on what ijack is 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);
}

How To Ask Questions The Smart Way


Report •
Related Solutions


Ask Question