【发布时间】:2014-03-15 19:14:46
【问题描述】:
我正在研究算法文本,尝试在 C++ 中实现所有内容以供练习。但我似乎无法弄清楚模板。我有三个文件: algPlayground.h
#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
我不知道我哪里出错了。帮忙?
【问题讨论】:
-
这不是向量的问题。拆分模板的声明和定义通常不是一个好主意。
标签: c++ templates c++11 vector instantiation