使用模板对字符串和字符进行排序
Using templates to sort strings and characters
我正在尝试使用模板对不同类型的数组进行从最小到最大的排序。
虽然我得到了正确排序的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";
当然,这个特定的模板只适用于基于堆栈的数组,而不适用于动态分配的数组,但您可以始终使用其他调用。
相关文章:
- 使用排序函数 c++ 对字符数组进行排序
- 非ASCII字符的词典排序
- 对向量<常量字符 *> 进行排序
- C++ MDC final-在字符类型的数组结构中按字母顺序对记录中的名称进行排序
- 按字母顺序排序字符数组,然后按长度排序
- 如何使用排序和比较这两个函数在 c++ 中对字符数组进行排序?
- 在字符串中对字符进行排序
- 多地图<矢量<int>>,字符>如何排序?
- C++ 从文件中读取字符,计算每个字符并进行排序
- 对包含整数和字符的字符串数组进行排序
- 使用气泡排序从类中对 2D 字符和 Int 数组进行排序
- 通过交换指针对字符数组进行排序,C++
- C++对2D字符数组进行气泡排序
- ASCII 艺术 - 按亮度级别对 ASCII 字符数组进行排序 (C/C++)
- 使用模板对字符串和字符进行排序
- 将字符串重新排序为没有连续相同字符的字符串
- C++ 对字符而不是整个字符串进行排序
- 正在对字符进行排序**
- 对包含特殊字符的 2D 数组进行排序 C++
- 首先按字符排序字符串