I am new to C ++ and kindly ask for help to solve the problem.
I am writing a simple STL style function that should return the middle element of a sequence (vector, list, etc.)
Here is my function, I am trying to use the iterator concept
template <class It, class T> It middle(It first, It last) { while(first!=last){ ++first; --last; } return first; }
here is my main one, trying to call middle for an ints vector (I skipped include)
int main() { vector<int>vi; int x; cout<<"Enter vector elemets..."; while (cin>>x) vi.push_back(x); cout<<endl; cin.clear(); cout<<"the vector is:"<<endl; for(int i=0;i<vi.size();++i) cout<<vi[i]<<" "; cout<<endl; vector<int>::iterator first=vi.begin(); vector<int>::iterator last=vi.end(); vector<int>::iterator ii=middle(first,last); cout<<"The middle element of the vector is: "<<*ii<<endl; }
When compiling with g ++, I get the following error:
myex21-7.cpp:79: error: no matching function for call to 'middle(__gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >&, __gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >&)'
Can someone give me some advice on how to fix it? Thanks for any help in advanced snacks.
source share