【问题标题】:C++ How to use vectors with templates? [duplicate]C++ 如何在模板中使用向量? [复制]
【发布时间】: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


【解决方案1】:

您的问题是您需要在头文件中实现模板。编译器需要能够在实例化模板时看到模板的实现,以便生成适当的代码。因此,只需将定义从 algPlayground.cpp 移动到 algPlayground.h

实现相同目的的另一种方法是反转#includes,以便在algPlayground.h 的底部是#include "algPlayground.cpp"。喜欢这种方法的人经常在实现文件中使用tpp 扩展名,以明确发生了什么。

【讨论】:

    【解决方案2】:

    问题是您的insertionSort&lt;T&gt; 模板没有在 algTest.cpp 文件中实例化。将模板的定义移动到头文件(推荐)或algTest.cpp,你应该很好。
    您可以查看this questionthat question 了解更多详情。

    【讨论】:

      猜你喜欢
      • 2014-09-18
      • 2016-09-07
      • 1970-01-01
      • 1970-01-01
      • 2015-05-29
      • 1970-01-01
      • 2021-05-17
      • 2021-10-20
      • 2011-06-17
      相关资源
      最近更新 更多