Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/133.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 将算法重写为模板函数以比较2个值_C++ - Fatal编程技术网

C++ 将算法重写为模板函数以比较2个值

C++ 将算法重写为模板函数以比较2个值,c++,C++,我试图将下面的选择排序算法重写为比较两个元素的模板函数 这是我的排序算法 #include <iostream> #include "util.h" /** Gets the position of the smallest element in a vector range. @param a the vector @param from the beginning of the range @param to the end of t

我试图将下面的选择排序算法重写为比较两个元素的模板函数

这是我的排序算法

    #include <iostream>

#include "util.h"

/** 
    Gets the position of the smallest element in a vector range.
    @param a the vector
    @param from the beginning of the range
    @param to the end of the range
    @return the position of the smallest element in 
    the range a[from]...a[to]
*/
int min_position(vector<int>& a, int from, int to)
{  
   int min_pos = from;
   int i;
   for (i = from + 1; i <= to; i++)
      if (a[i] < a[min_pos]) min_pos = i;
   return min_pos;
}

/** 
   Sorts a vector using the selection sort algorithm
   @param a the vector to sort
*/

void selection_sort(vector<int>& a)
{  
   int next; // The next position to be set to the minimum

   for (next = 0; next < a.size() - 1; next++)
   {  
      // Find the position of the minimum
      int min_pos = min_position(a, next, a.size() - 1);
      if (min_pos != next)
         swap(a[min_pos], a[next]);
   }
}

int main()
{  
   rand_seed();
   vector<int> v(20);
   for (int i = 0; i < v.size(); i++)
      v[i] = rand_int(1, 100);
   print(v);
   selection_sort(v);
   print(v);
   return 0;
}
#包括
#包括“util.h”
/** 
获取向量范围中最小元素的位置。
@向量的参数a
@从范围的开头开始的参数
@参数设置为范围的末尾
@返回中最小元素的位置
范围a[从]…a[到]
*/
int最小位置(向量&a,int-from,int-to)
{  
int min_pos=从;
int i;
对于(i=从+1;i 0){
if(A[k-1]>移动器){
A[k]=A[k-1];
k--;
}否则
打破
}
A[k]=移动器;
} 
}
<>我是C++新手,模板/排序是适合我的,所以我在寻找一些帮助或指导。
谢谢

你能用
std::sort
而不是自己写吗?这是练习吗?另外,
min\u位置
已作为
std::min\u元素
存在。如果您能告诉我们您有什么问题,这将对我们有所帮助。@Mark Yes这是课堂练习。我的原始程序可以进行排序,但我不知道如何将程序作为函数重写。我可以独立编写函数,我做到了,但是我在重写程序时遇到了困难。
template <typename T> 
void sort(T A[],int N) 
{  

 for(int n = 1;n < N;n++) {
     T mover = A[n];
     int k = n;
     while(k > 0) {
       if(A[k-1] > mover) {
         A[k] = A[k-1];
        k--;
       } else
         break;
     }
     A[k] = mover;   
} 

}