我正在通過算法文本工作,試圖在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
我不知道我在這裏錯了。幫幫我?
這對於矢量尤其不是問題。一般來說,拆分模板的聲明和定義並不是一個好主意。 – Paranaix