祝大家新年快樂啦 OuO
記錄一下把 C++ 中的 vector 函式改成 template
只改 vector 是頗容易,但是加上 iterator 就出現錯誤
原本只能使用 int 當作元素的函式
void print_vector(vector<int> a)
{
    vector<int>::iterator iter;
    for (iter = a.begin(); iter != a.end(); iter++) {
        printf("%d ", *iter);
    }
    printf("\n");
}
修改後:
主要要注意的是 vector
(missing 'typename' prior to dependent type name 'vector
優點:可使用其他型別,e.g. long long, double 或其他有 overriding << 運算子的 class
template <class T>
void print_vector(vector<T> a)
{
    typename vector<T>::iterator iter;
    for (iter = a.begin(); iter != a.end(); iter++) {
        printf("%s", (iter == a.begin())? "": " ");
        cout << *iter;
    }
    printf("\n");
}
修改後完整程式碼(含測試):
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <vector>
using namespace std;
template <class T>
void print_vector(vector<T> a)
{
    typename vector<T>::iterator iter;
    for (iter = a.begin(); iter != a.end(); iter++) {
        printf("%s", (iter == a.begin())? "": " ");
        cout << *iter;
    }
    printf("\n");
}
int main()
{
    vector<double> a({-1, 16, 4, 10, 14, 7, 9, 3, 2, 8, 1});
    print_vector(a);
    return 0;
}
參考資料:
C++ template typename iterator
沒有留言:
張貼留言