将迭代器传递给模板

Passing iterators to templates

本文关键字:迭代器      更新时间:2023-10-16

很抱歉这个问题不清楚。我需要使用以下模板使用插入算法对属于自定义类的对象数组进行排序:

template<typename pointer, typename T, typename Functype>
void sort_array(pointer puntatore, T* obj, int dim, Functype pred){
    T val;
    for(int i=1; i<dim; i++){
        val=obj[i];
        for(int j=(i-1); j>=0; j--){
            if(pred(obj[j].*puntatore, val.*puntatore)){
                obj[j+1]=obj[j];
                obj[j]=val;
            }
        }
    }
}

我想知道如何编写一个更通用的模板,该模板可以接受指向类 T 对象的任何类型的迭代器,而不仅仅是指针。在参数列表中写入T obj会给我在赋值中的变量T val带来麻烦,在这种情况下,这就像*val=obj[i] val本身是一个迭代器。有没有办法告诉模板他必须接受指向类 T 对象的通用迭代器(即以相同的方式编写T*告诉它期望指向类 T 对象的指针)?

我如何使用此模板的示例

class Example{
   int first;
   int second;
};
template<typename pointer, typename T, typename Functype>
void sort_array(pointer puntatore, T* obj, int dim, Functype pred){
    T val;
    for(int i=1; i<dim; i++){
        val=obj[i];
        for(int j=(i-1); j>=0; j--){
            if(pred(obj[j].*puntatore, val.*puntatore)){
                obj[j+1]=obj[j];
                obj[j]=val;
            }
        }
    }
}
int main(){
    Example array[5]={{1,2},{2,4},{1,7},{5,3},{6,7}};
    //now i sort the elements in the array by their first element in a decreasing order
    sort_array(&Example::first, array, 5, [](int a, int b){return (a<b);});

}
好吧,

你可以从 STL 实现中汲取灵感,提供一个接口,该接口将采用一个范围而不是如下所示的数组:

template<typename BidirectionalIterator, typename Predicate = 
  std::less<typename std::iterator_traits<BidirectionalIterator>::value_type>>
void
insertion_sort(BidirectionalIterator first, BidirectionalIterator last, 
  Predicate pred = {}) {
  if(first != last) {
    auto it = first; 
    while(++it != last) {
      auto it2 = it;
      while(it2 != first) {
        auto it3 = it2;
        --it3;
        if(pred(*it2, *it3)) {
          std::swap(*it2, *it3);
        } else {
          break;
        }
        --it2;
      }
    }
  }
}

现场演示

但请注意,您还可以为对象提供重载operator<operator>,以便与标准谓词一起使用:

bool
operator<(T const &A, T const &B) {
  return A.*puntatore < B.*puntatore;
}

bool
operator>(T const &A, T const &B) {
  return A.*puntatore < B.*puntatore;
}