所有类型的STL容器的通用排序

时间:2019-05-11 17:53:17

标签: c++

我正在学习C ++ iterator_traits ,通过它我对所有C ++ STL容器(std :: vector,std :: forward_list等)实施通用排序。但是在完成此功能时我遇到了一些问题。这是我的示例代码:

#include<iostream>
#include<vector>
#include<forward_list>
#include<iterator>


template<typename For>
void sortHelper(For beg, For end, std::forward_iterator_tag)
{
    std::vector<decltype(*beg)> Temp {beg, end};
    std::sort(Temp.begin(), Temp.end());
    std::copy(Temp.begin(), Temp.end(), beg);
}


template<typename Ran>
void sortHelper(Ran beg, Ran end, std::random_access_iterator_tag)
{
    std::sort(beg, end);
}


template<typename Container>
void sortData(Container& cont)
{
    sortHelper(cont.begin(), cont.end(), typename std::iterator_traits<typename Container::iterator>::iterator_category);
}


int main(int argc, char* argv[])
{
    std::vector<int> VectorList {223, 234, 45, 6456, 556, 34324, 678, 1231};
    std::forward_list<int> ForwardList {234234, 345345, 31, 456, 454, 34, 3242, 96};

    std::cout << "Before sorting VectorList:" << std::endl;
    for(auto x : VectorList)
        std::cout << x <<"\t";
    std::cout << std::endl;

    std::cout << "Before sorting ForwardList:" << std::endl;
    for(auto x : ForwardList)
        std::cout << x <<"\t";
    std::cout << std::endl;

    sortData(VectorList);
    sortData(ForwardList);

    std::cout << "After sorting VectorList:" << std::endl;
    for(auto x : VectorList)
        std::cout << x <<"\t";
    std::cout << std::endl;

    std::cout << "After sorting ForwardList:" << std::endl;
    for(auto x : ForwardList)
        std::cout << x <<"\t";
    std::cout << std::endl;

    return 0;
}

我遇到以下编译器错误

Test2.cpp:25:117: error: expected ‘(’ before ‘)’ token
  sortHelper(cont.begin(), cont.end(), typename std::iterator_traits<typename Container::iterator>::iterator_category);

0 个答案:

没有答案