我正在使用CMake(CLion)进行课堂项目。我尝试了以下解决方案,但它们不起作用:1,2,3。
我为一个类项目创建了一个HeapSort类,我需要使用它来对字符串向量(字典)进行排序。我在这个字典中创建了一个HeapSort类的实例,如下所示:
void Dictionary::heapSort()
{
Heap<std::string> h;
stringDict = h.heapSort(stringDict);
}
我不断获得构造函数和heapSort()
函数的未定义引用,其中类定义如下(heapSort()
类似):
Heap.cpp
#include "Heap.h"
template <typename T>
Heap<T>::Heap() {}
template <typename T>
void Heap<T>::initializeMaxHeap(std::vector<T> v)
{
heap = v;
heapSize = heap.size();
}
template <typename T>
void Heap<T>::maxHeapify(int i)
{
int l = left(i);
int r = right(i);
int large;
if (l <= heapSize && heap.at(l) > heap.at(i))
large = l;
else
large = i;
if (r <= heapSize && heap.at(r) > heap.at(i))
large = r;
if (large != i)
{
std::swap(heap.at(i), heap.at(large));
maxHeapify(large);
}
}
template <typename T>
void Heap<T>::buildMaxHeap()
{
for (int i = std::floor(heap.size()/2); i > 1; i++)
maxHeapify(i);
}
template <typename T>
std::vector<T> Heap<T>::heapSort(std::vector<T> v)
{
initializeMaxHeap(v);
buildMaxHeap();
for (int i = heap.size(); i > 2; i++)
{
std::swap(heap.at(1), heap.at(i));
heapSize--;
maxHeapify(1);
}
return heap;
}
Heap.h
#ifndef PROJ3_HEAP_H
#define PROJ3_HEAP_H
#include <cmath>
#include <vector>
#include "Dictionary.h"
template <typename T>
class Heap
{
private:
std::vector<T> heap;
int heapSize;
public:
Heap();
int parent(int index) { return index/2; };
int left(int index) { return index * 2; };
int right(int index) { return index * 2 + 1; };
int getItem(int index) { return heap.at(index); };
void initializeMaxHeap(std::vector<T> v);
void maxHeapify(int i);
void buildMaxHeap();
std::vector<T> heapSort(std::vector<T> v);
};
#endif //PROJ3_HEAP_H
的CMakeLists.txt
cmake_minimum_required(VERSION 3.6)
project(proj3)
set(CMAKE_CXX_STANDARD 11)
set(SOURCE_FILES main.cpp Dictionary.cpp Dictionary.h Grid.cpp Grid.h Heap.cpp Heap.h)
add_executable(proj3 ${SOURCE_FILES})
现在,我将所有文件放在一个文件夹中。我此时应该在CMakeLists.txt
添加什么内容?我尝试add_library/target_link_library
(使用不同的命令),添加include_directories
,我尝试在我的目录中单独构建每个类,将它们链接到主可执行文件。我是否还需要重新组织我的目录?
编辑:添加了Heap.cpp&amp; Heap.h