So I am in the midst of reading Stroupstrup's book, The Programming Language 4th ed, and I came upon this little program to help us sort singly linked containers that do not provide random iterator access to the data. Basically, he writes an "adapter" (I hope I'm using the term correctly) to sort a singly linked list by copying the singly linked list into a vector, sorting the vector, and then copying back the vector into a singly linked list. The neat, and confusing part is some of the commands he uses, which I was hoping someone could explain:
void test(vector<string>& v, forward_list<int>& lst) {
sort(lst); //sort the singly linked list
}
He writes two helper functions that take an extra argument indicating whether the sort is to be used for singly-linked iterators or random iterators:
template<typename Ran> //for random access iterators
void sort_helper(Ran beg, Ran end, random_access_iterator_tag) //we can subscript into [beg:end)
{
sort(beg,end); //just sort it
}
and
template<typename For> //for forward iterators
void sort_helper(For beg, For end, forward_iterator_tag) //we can traverse [beg:end)
{
vector<decltype(*beg)> v {beg,end}; //initialize the vector
sort(v.begin(),v.end());
copy(v.begin(),v.end(),beg); //copy the elements back
}
QUESTION: I have never seen the paramters of a function be in the format "forward_iterator_tag", I have always only seen "Type instance" ie "int myInt". What is "forward_iterator_tag", and where is its type?
The selection of the helper function happens here:
template<typname C>
void sort(C& c) {
using Iter = Iterator_type<C>;
sort_helper(c.begin(),c.end(),Iterator_category<Iter>{});
}
QUESTION:
1)How would this sort template look if we were to not have using Iter = Iterator_type<C>;? What does this line do? - I have never seen it used in this context.
2)What is Iterator_type and Iterator_category? I searched for these on
www.cplusplus.com but found nothing that would make it clear.
Thanks to all for reading something this long.