使用模板对字符串和字符进行排序

Using templates to sort strings and characters

本文关键字:字符 排序 字符串      更新时间:2023-10-16

我正在尝试使用模板对不同类型的数组进行从最小到最大的排序。

虽然我得到了正确排序的int数组,但我无法从排序中得到字符或字符串数组。我一直收到一个错误,上面写着"对bsort(char[10],int)的调用没有匹配的函数"answers"bsort(std::string[10],int)"。我做错了什么?

在我的模板中,我认为通过"Object"声明,它可以适应所有不同的类型。

#include <iostream>
#include <string>
using namespace std;

template <class Object>
void bsort(Object a[], Object n)
{
    for (int i=0; i<n-1; i++)
    {
        for (int j=i+1; j<n; j++)
            {
                if(a[i]>a[j])
                {
                    Object item;
                    item=a[i];
                    a[i]=a[j];
                    a[j]=item;
                }
            }
    }
 }

 int main ()
 {
    int intarray[10]= {50, 10, 20, 15, 62, 32, 6, 80, 90, 100};
    char chararray[10]= {'a', 'f', 'v', 'b', 'c', 's', 'm', 'i', 'j', 'i'};
    string stringarray[10]= {"hi", "how", "are", "you", "today", "love", "eating", "food", "brownies", "icecream"};
cout<<"The intarray consists of"<<endl;
for (int i=0; i<10; i++)
    cout<<intarray[i]<<endl;
cout<<"The sorted intarray sorted is"<<endl;
bsort(intarray, 10);
for (int i=0; i<10; i++)
    cout<<intarray[i]<<endl;
cout<<"Sorted char array"<<endl;
bsort(chararray, 10);
for (int i=0; i<10; i++)
    cout<<chararray[i]<<endl;
cout<<"The sorted stringarray is"<<endl;
bsort(stringarray, 10);
for (int i=0; i<10; i++)
    cout<<stringarray[i]<<endl;
return 0;

}

**编辑,我一开始尝试了一个[],但它仍然没有改变它给我的排序/错误

void bsort(Object *array, Object n)

应该是

void bsort(Object *array, std::size_t n)

演示

您还可以利用模板推导,这样您就不必每次都提供类型或大小。

template <class Object>
void bsort(Object *array, int n) {
    for (int i = 0; i < n - 1; ++i) {
        for (int j = i + 1; j<n; ++j){
            if (array[i] > array[j]) {
                Object item;
                item = array[i];
                array[i] = array[j];
                array[j] = item;
            }
        }
    }
}

这很好,但每次都必须提供一个尺寸。如果你这样声明,这可能会很烦人:

intarray[] = {3, 1, 5, 2, 0, 8, 6, 9, 4, 7}; // do you really want to count these?

为此,您可以创建一个非常简单的模板包装器(我放了两个):

template<class Object, size_t N>
void bsort(Object(&o)[N]) {
    return bsort<Object>(o, N);
}
template<class Object, size_t N>
void bsort(Object(&o)[N], size_t &size) {
    size = N;
    return bsort<Object>(o, N);
}

第二个原因是,您可以将size_t ref传递给它,它会将其设置为大小。例如,您可以运行以下任一项:

int intarray[] = {3, 1, 5, 2, 0, 8, 6, 9, 4, 7};
bsort(intarray);
bsort<int>(intarray, 10); // <int> is rather unnecessary
size_t size = 0;
bsort(intarray, size);

你可能想使用最后一个是因为现在你有了打印正确尺寸的方法。

int intarray[] = {3, 1, 5, 2, 0, 8, 6, 9, 4, 7};
size_t size = 0;
bsort(intarray, size);
for(size_t i = 0; i < size; ++i)
    std::cout << intarray[i] << "n";

当然,这个特定的模板只适用于基于堆栈的数组,而不适用于动态分配的数组,但您可以始终使用其他调用。