如何创建一个接受数组和向量引用的函数模板?

时间:2014-10-18 16:27:07

标签: c++ arrays templates vector

如何创建一个接受数组和向量引用的函数模板?

当然我有一个需要接受数组或向量的函数模板,它会对条目进行排序。截至目前,它只接受数组。

代码:

template <class T, class B>
class SelectionSort
{
    public:
        void IterativeSort(T &data, B size)
        {

            for (unsigned int index = 0; index < size; index++)
            {
                int smallestNum = index;

                for (unsigned int inner = index; inner < size; inner++)
                {
                    if (data[smallestNum]>data[inner])
                    {
                        smallestNum = inner;
                    }
                }


                int temp = data[smallestNum];
                data[smallestNum] = data[index];
                data[index] = temp;
            }


        }
}

数组调用:

//  sort copy of small array with iteration
SelectionSort<int, int> smallArrayIterativeSort;
smallArrayIterativeSort.IterativeSort(copySmallArray, smallSize);

矢量调用:

//  sort small vector with iteration
SelectionSort<vector <int>, int> smallVectorIterativeSort;
smallVectorIterativeSort.IterativeSort(smallVector, smallSize);

2 个答案:

答案 0 :(得分:1)

我很想创建一个带有迭代器的模板函数,而不是对象本身。

有点像这样:

template<typename Iterator>
void IterativeSort(Iterator begin, Iterator end)
{
    for(Iterator index = begin; index != end; ++index)
    {
        Iterator smallestNum = index; 

        for(Iterator inner = index; inner != end; ++inner)
        {
            if(*smallestNum > *inner)
                smalestNum = inner;
        }

        // etc....

    }
}

int main()
{
    int array[1024];
    std::vector<int> vec(1024);

    IterativeSort(array, array + sizeof(array)/sizeof(int));
    IterativeSort(vec.begin(), vec.end());
}

答案 1 :(得分:0)

你可以进行两次重载,一次用于std :: vector,另一次用于数组。

#include <iostream>
#include <vector>

template <class T, class B>
class SelectionSort
{
public:
    void IterativeSort(T data[], B size)
    {
        for (unsigned int index = 0; index < size; index++)
        {
            int smallestNum = index;

            for (unsigned int inner = index; inner < size; inner++)
            {
                if (data[smallestNum]>data[inner])
                {
                    smallestNum = inner;
                }
            }


            int temp = data[smallestNum];
            data[smallestNum] = data[index];
            data[index] = temp;
        }
    }

    void IterativeSort(std::vector<T> &data, B size)
    {
        IterativeSort(&data[0], size);
    }
};

int main() {
    std::vector<int> smallVector(20);
    int copySmallArray[20];
    int smallSize = 20;

    SelectionSort<int, int> smallArrayIterativeSort;
    smallArrayIterativeSort.IterativeSort(copySmallArray, smallSize);
    smallArrayIterativeSort.IterativeSort(smallVector, smallSize);

    return 0;
}