以排序算法讲解C++基础项目结构
目录
[1. SortAlgorithms.h (头文件 - 函数声明)](#1. SortAlgorithms.h (头文件 - 函数声明))
[2. SortAlgorithms.cpp (源文件 - 函数定义)](#2. SortAlgorithms.cpp (源文件 - 函数定义))
[3. main.cpp (主程序文件)](#3. main.cpp (主程序文件))
[Visual Studio中的文件组织:](#Visual Studio中的文件组织:)
[在Visual Studio中创建步骤:](#在Visual Studio中创建步骤:)
头文件保护(#ifndef/#define/#endif))
典型的C++项目结构,按照Visual Studio的习惯,可以将代码分为头文件(.h)和源文件(.cpp)。
项目结构建议:
1. SortAlgorithms.h (头文件 - 函数声明)
#ifndef SORTALGORITHMS_H
#define SORTALGORITHMS_H
#include <iostream>
#include <vector>
using namespace std;
// 函数声明
void insertionSortWithSteps(vector<int>& arr);
#endif // SORTALGORITHMS_H
2. SortAlgorithms.cpp (源文件 - 函数定义)
#include "SortAlgorithms.h"
// 直接插入排序函数定义(带步骤输出)
void insertionSortWithSteps(vector<int>& arr) {
int n = arr.size();
for (int i = 1; i < n; i++) {
int key = arr[i];
int j = i - 1;
cout << "\n第" << i << "轮: 插入 " << key << endl;
cout << " 当前状态: ";
for (int k = 0; k < n; k++) {
if (k == i) cout << "| ";
cout << arr[k] << " ";
}
cout << endl;
// 移动元素
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
// 插入元素
arr[j + 1] = key;
cout << " 插入后: ";
for (int k = 0; k < n; k++) {
cout << arr[k] << " ";
}
cout << endl;
}
}
3. main.cpp (主程序文件)
#include "SortAlgorithms.h"
int main() {
vector<int> arr = {5, 2, 4, 6, 1, 3};
cout << "直接插入排序过程:" << endl;
cout << "初始数组: ";
for (int num : arr) {
cout << num << " ";
}
cout << endl;
insertionSortWithSteps(arr);
cout << "\n最终排序结果: ";
for (int num : arr) {
cout << num << " ";
}
cout << endl;
return 0;
}
Visual Studio中的文件组织:
文件结构:
你的项目文件夹/
│
├── SortAlgorithms.h (头文件 - 包含函数声明)
├── SortAlgorithms.cpp (源文件 - 包含函数定义)
└── main.cpp (主文件 - 包含main函数)
在Visual Studio中创建步骤:
-
创建新项目:选择"控制台应用"
-
添加文件:
-
在"解决方案资源管理器"中右键"头文件" → 添加 → 新建项 → 选择"头文件(.h)" → 命名为
SortAlgorithms.h -
在"源文件"上右键 → 添加 → 新建项 → 选择"C++文件(.cpp)" → 命名为
SortAlgorithms.cpp -
修改现有的
main.cpp(或添加一个新的)
-
-
编译运行:按F5或Ctrl+F5编译运行
文件类型的说明:
-
.h 文件 (头文件):包含函数声明、类声明、宏定义、类型定义等
-
.cpp 文件 (源文件):包含函数定义、类方法的实现
-
main.cpp (主源文件):包含main()函数,程序的入口点
头文件保护(#ifndef/#define/#endif)
没有头文件保护:
// 假设在main.cpp中:
#include "myheader.h"
#include "myheader.h" // 重复包含,会导致编译错误!
有头文件保护:
// myheader.h
#ifndef MYHEADER_H // 如果MYHEADER_H没有被定义
#define MYHEADER_H // 定义MYHEADER_H
// 头文件的实际内容
void myFunction();
int myVariable = 10;
#endif // 结束