程序中模板类型的输入打印错误

Inputs are printed wrongly of template types in program

本文关键字:输入 打印 错误 类型 程序      更新时间:2023-10-16

这是我的程序与模板的代码片段。它没有错误,但是当我打印时,它会产生错误的结果。请告诉我哪里错了,我该如何解决这个问题。下面是具有三个函数和一个带有模板 T 的主函数的C++代码。

#include<iostream>
using namespace std;
template<typename T>
void input(T* &start, int size){
    start = new T[size];
    T* beyond = &start[size];
    while(start != beyond){
        cout<<"nEnter: ";
        cin>>*start;
        start++;
    }
}

template<typename T>
void sort(T* start, int size){
    T hold;
    for(int j=0; j<size-1; j++){
        for(int i=0; i<size-1; i++){
            if(start[i]>start[i+1]){
                    hold=start[i];
                    start[i]=start[i+1];
                    start[i+1]=hold;
            }
        }
    }
}

template<typename T>
void display(T* start, int size){
    T* beyond = &start[size];
    cout<<"nAfter Sorting: "<<endl;
    while(start != beyond){
        cout<<*start<<"t";
        start++;
    }
}
int main(){
    int* x=NULL;
    float* y=NULL;
    char* z=NULL;
    int size;
    cout<<"Enter the number of elements: ";
    cin>>size;
    cout<<"nEnter integer values:";
    input<int>(x, size);
    sort<int>(x, size);
    display<int>(x, size);
/** 
    cout<<"nEnter floating values:";
    input<float, int>(y, size);
    sort<float, int>(y, size);
    display<float, int>(y, size);
    cout<<"nEnter character values:";
    input<char, int>(z, size);
    sort<char, int>(z, size);
    display<char, int>(z, size);
    */
    system("pause");
}

input函数中,您分配内存并将其置于start。然后,将该指针移动到末尾,该结束值将返回到调用函数。然后,您尝试将其用作其他方法的开始,这将导致未定义的行为。

template<typename T>
void input(T* &start, int size){
    start = new T[size]; // points to the start
    T* beyond = &start[size];
    while(start != beyond){
        cout<<"nEnter: ";
        cin>>*start;
        start++; // Moving all the time...
    }
    // In the end start points to beyond and main gets that as a result
}

如果你真的想玩指针,你可以很容易地修复它:

template<typename T>
void input(T* &start, int size){
    start = new T[size];
    T* beyond = &start[size];
    T* curr = start;
    while(curr != beyond){
        cout<<"nEnter: ";
        cin>>*curr;
        curr++;
    }
}

这样,start指针将始终指向开头,并正确返回到调用函数。

在调试器中逐步运行将很容易显示此问题。另外,请始终描述问题,如果您不解释正确的结果是什么或您得到的结果,我们不知道"生成错误的结果"是什么意思,而是使用某些输入。

你可以这样做:

template<typename T>
void input(T* &start, int size){
    start = new T[size];
    //T* beyond = &start[size-1];
    //while(start <= beyond){
    for(int i=0;i<size;i++){
        cout<<"nEnter: ";
        cin>>start[i];
        //start++;
    }
    //}
}

和:

template<typename T>
void display(T* start, int size){
    //T* beyond = &start[size-1];
    cout<<"nAfter Sorting: "<<endl;
    for(int i=0;i<size;i++){
        cout<<start[i]<<"t";
    }
}

这是一种更简单的形式,可以做你想做的事情,并且有效。