S
Senthilvel
Hi folks,
I was trying to learn the standard library algorithms where i got stuck with
the templates.
I wrote one function to eliminate the duplicates(from The C++ Programming
Language 3rd Edition)
template<class Con> void RemoveDuplicates(Con& seq)
{
sort(seq.begin(),seq.end());
typename Con::iterator p = unique(seq.begin(),seq.end());
seq.erase(p,seq.end());
}
int main()
{
vector<int> ls1;
ls1.push_back(1);
ls1.push_back(2);
ls1.push_back(3);
ls1.push_back(4);
ls1.push_back(1);
ls1.push_back(2);
ls1.push_back(3);
ls1.push_back(4);
print_all(ls1,cout);
RemoveDuplicates(ls1);
print_all(ls1,cout);
return 0;
}
This worked fine for vector,deque but failed for list as sort needs randon
access iterators which is not provided by list
So i thought of specializing the function for list, but how do i do it ???
List needs a template argument and i do not know how to pass that
template argument.I did this way
template<class T> void RemoveDuplicates(list<T> & seq)
{
seq.sort();
typename list<T>::iterator p = unique(seq.begin(),seq.end());
seq.erase(p,seq.end());
}
int main()
{
list<int> ls1;
ls1.push_back(1);
ls1.push_back(2);
ls1.push_back(3);
ls1.push_back(4);
ls1.push_back(1);
ls1.push_back(2);
ls1.push_back(3);
ls1.push_back(4);
print_all(ls1,cout);
RemoveDuplicates<int>(ls1);
print_all(ls1,cout);
return 0;
}
Now i explicity need to specify the type in the RemoveDuplicates function.
Am i correct or am i missing something ???
Thanks and Best Regards,
Senthilvel.
I was trying to learn the standard library algorithms where i got stuck with
the templates.
I wrote one function to eliminate the duplicates(from The C++ Programming
Language 3rd Edition)
template<class Con> void RemoveDuplicates(Con& seq)
{
sort(seq.begin(),seq.end());
typename Con::iterator p = unique(seq.begin(),seq.end());
seq.erase(p,seq.end());
}
int main()
{
vector<int> ls1;
ls1.push_back(1);
ls1.push_back(2);
ls1.push_back(3);
ls1.push_back(4);
ls1.push_back(1);
ls1.push_back(2);
ls1.push_back(3);
ls1.push_back(4);
print_all(ls1,cout);
RemoveDuplicates(ls1);
print_all(ls1,cout);
return 0;
}
This worked fine for vector,deque but failed for list as sort needs randon
access iterators which is not provided by list
So i thought of specializing the function for list, but how do i do it ???
List needs a template argument and i do not know how to pass that
template argument.I did this way
template<class T> void RemoveDuplicates(list<T> & seq)
{
seq.sort();
typename list<T>::iterator p = unique(seq.begin(),seq.end());
seq.erase(p,seq.end());
}
int main()
{
list<int> ls1;
ls1.push_back(1);
ls1.push_back(2);
ls1.push_back(3);
ls1.push_back(4);
ls1.push_back(1);
ls1.push_back(2);
ls1.push_back(3);
ls1.push_back(4);
print_all(ls1,cout);
RemoveDuplicates<int>(ls1);
print_all(ls1,cout);
return 0;
}
Now i explicity need to specify the type in the RemoveDuplicates function.
Am i correct or am i missing something ???
Thanks and Best Regards,
Senthilvel.