需要使用模板查找数组的第二到最小和最小值

时间:2018-09-29 21:11:52

标签: c++ templates

我已经声明了main内部数组的长度,但是由于用户可以为数组的第一个值输入较小的值,因此我不能仅将排序变量分配为a [0]。它给了我最小值,但是第二个最小值也总是返回最小值。

template < class T >
T smalls(T *a, const int n)
{
    T small;
    T smallest;

    for (int i =0; i<n ; i++)
    {
        if (smallest > a[i])
        {
            small = smallest;
            smallest = a[i];
        }
            cout << "Smallest value of array: ";
            cout << smallest << endl;
            cout << "Second smallest value of array: ";
            cout << small << endl;
}

1 个答案:

答案 0 :(得分:0)

您永远不会测试小与小。试试这个。

if (small > a[i])
{
    small = a[i];
    if (small < smallest)
        std::swap(small,smallest);
}
相关问题