尝试自定义一个函数来对不同种类元素的向量进行排序



我想写一个有点像stl中的排序的函数。这是我主要功能的一部分

inline bool myCmp(const int & a, const int & b) {
return a > b;
 }
 int main() {
int n, * s, i;
std::vector<int> v;
std::list<int> l;
std::cin >> n;
s = new int[n];
for (i = 0; i < n; ++i) {
    std::cin >> s[i];
    v.push_back(s[i]);
    l.push_back(s[i]);
}
mySort(v.begin(), v.end(), myCmp);
mySort(l.begin(), l.end());

我在这里实现了我的排序功能

    template <typename T>
typedef bool (*pf)(const T& ,const T&);
template <typename T>
void mySort(T a, T b, pf = nullptr)
{
  for(auto i = a; i != b; i++)
  {
    for(auto j = a + 1; j != b; j++)
    {
      if(i >  j)
      {
        T temp = i;
        i = j;
        j = temp;
      }
    }
  }
}

不幸的是,我遇到了一些错误,

    sort.h: In instantiation of 'void mySort(T, T, pf) [with T = std::_List_iterator<int>; pf = bool (*)(const int&, const int&)]':
main.cpp:22:30:   required from here
sort.h:8:20: error: no match for 'operator+' (operand types are 'std::_List_iterator<int>' and 'int')
     for(auto j = a + 1; j != b; j++)
                    ^
In file included from /usr/include/c++/5/bits/stl_algobase.h:67:0,
                 from /usr/include/c++/5/vector:60,
                 from main.cpp:1:
/usr/include/c++/5/bits/stl_iterator.h:334:5: note: candidate: template<class _Iterator> std::reverse_iterator<_Iterator> std::operator+(typename std::reverse_iterator<_Iterator>::difference_type, const std::reverse_iterator<_Iterator>&)
     operator+(typename reverse_iterator<_Iterator>::difference_type __n,
     ^
/usr/include/c++/5/bits/stl_iterator.h:334:5: note:   template argument deduction/substitution failed:
In file included from main.cpp:4:0:

那么运算符"+"有什么问题呢?我怎样才能成功地编写这个 mySort 函数?提前感谢!

问题是,在行中:

mySort(l.begin(), l.end());

而在里面,

for(auto j = a + 1; j != b; j++)
             ^^^^^

您正在尝试访问列表迭代器operator+。但是 std::list<T>::begin/end 返回的迭代器是一个双向迭代器。双向迭代器未定义operator+。不过,您可以使用operator++

另一方面,std::vectorstd::vector<T>::begin/end 返回随机访问迭代器。随机访问迭代器确实定义了operator+

因此,请尝试以下操作:

for(auto i = a; i != b; i++)
{
    auto c = a;
    for(auto j = ++c; j != b; j++)
    {
        ...

最新更新