0

I'm trying to write my own sort function that can sort vector container.

I'm hoping to call it in the following manner:

this:sort(arr.begin() , arr.end() - 1)

arr.end() - 1 - because arr.end() returns the next element, actually not element, returns iterator to end.

So i want to call my function with iterator on any type.I tried to run this code:

#include<iostream>
#include<vector> 
using namespace std;

template<typename T1> 
void func(vector<T1>::iterator it) {
    cout << "\n" << *it; 
}

int main() {
    vector<int> arr(10);

    for(int i = 0;i < 10;++i)
        arr[i] = i+1;

    func<int>(arr.begin()); 
}

But compiler says:

main.cpp:10:23: error: variable or field ‘func’ declared void  void func(vector<T1>::iterator it)
                              main.cpp:10:32: error: expected ‘)’ before ‘it’  void func(vector<T1>::iterator it)
                                 main.cpp: In function ‘int main()’: main.cpp:26:5: error: ‘func’ was not declared in this scope
     func<int>(arr.begin());
     func main.cpp:26:10: error: expected primary-expression before ‘int’
     func<int>(arr.begin());

Please explain me my mistake.Thanks

1 Answers1

1

Compiler doesn't know that iterator is a type inside vector<T1>

template<typename T1> void func(typename vector<T1>::iterator it) {
    cout << "\n" << *it; }

Inside a template, some constructs have semantics which may differ from one instantiation to another. Such a construct depends on the template parameters.

You should write typename for such dependent types.

Yola
  • 18,496
  • 11
  • 65
  • 106