2014-02-16 31 views
0

我正在通過算法文本工作,試圖在C++中實現一切。但我似乎無法找出templating.I有三個文件: algPlayground.hC++如何使用具有模板的向量?

#include <stdlib.h> 
#include <vector> 

using namespace std; 

template <class T> void insertionSort(vector<T>& toSort); 

algPlayground.cpp

#include <stdlib.h> 
#include <vector> 
#include "algPlayground.h" 

using namespace std; 

template <class T> void insertionSort(vector<T>& toSort) { 
    for (int j=1; j < toSort.size(); ++j) { 
     T key = toSort[j]; 
     int i = j-1; 

     while (i > -1 && toSort[i] > key) { 
      toSort[i+1] = toSort[i]; 
      i -= 1; 
     } // end while 

    toSort[i+1] = key; 

    } // end for 

} // end insertionSort 

和algTest.cpp

#include <stdlib.h> 
#include <vector> 
#include <iostream> 
#include "algPlayground.h" 

using namespace std; 

int main() { 

    vector<int> vectorPrime(5); 

    vectorPrime[0]=5; 
    vectorPrime[1]=3; 
    vectorPrime[2]=17; 
    vectorPrime[3]=8; 
    vectorPrime[4]=-3; 

    insertionSort(vectorPrime); 
    for (int i=0; i<vectorPrime.size(); ++i) { 
     cout << vectorPrime[i] << " "; 
    }// end for 
} 

我得到出現以下錯誤:

algTest.cpp:(.text+0xb1): undefined reference to `void insertionSort<int>(std::vector<int, std::allocator<int> >&)' 
collect2: error: ld returned 1 exit status 

我看到this thread哪裏,有人提出,這樣做的正確方法是

template<typename T, typename A> 
void some_func(std::vector<T,A> const& vec) { 
} 

,但是當我作出這樣的修正,我仍然得到類似的錯誤:

algTest.cpp:(.text+0xb1): undefined reference to `void insertionSort<int, std::allocator<int> >(std::vector<int, std::allocator<int> >&)' 
collect2: error: ld returned 1 exit status 

我不知道我在這裏錯了。幫幫我?

+0

這對於矢量尤其不是問題。一般來說,拆分模板的聲明和定義並不是一個好主意。 – Paranaix

回答

2

你的問題是你需要在頭文件中實現模板。編譯器需要能夠在實例化時看到模板的實現,以便它可以生成適當的代碼。所以只需將定義從algPlayground.cpp移到algPlayground.h即可。

實現相同目標的另一種方法是將#include s倒過來,以便在algPlayground.h的底部您#include "algPlayground.cpp"。喜歡這種方法的人通常會使用tpp擴展名爲實現文件來明確發生了什麼。

1

問題是您的insertionSort<T>模板沒有在algTest.cpp文件中實例化。將模板的定義移動到頭文件(推薦)或algTest.cpp,你應該很好。
您可以檢查this questionthat question瞭解更多詳情。

相關問題