梦想不会自己发光,真正闪耀的是那个为梦狂奔的你。献给知行的孩子们!(Eric.He著)
枚举算法在小规模数据查找与匹配场景中应用广泛,核心是通过逐一遍历数据并验证匹配条件,实现简单可靠的查找效果。以下是 6 个典型实例,覆盖不同数据类型与匹配场景:
问题描述:
算法解析:
#include <iostream>
using namespace std;
int main() {
cout << "1~50之间的所有偶数:" << endl;
// 枚举所有候选数,逐一验证匹配条件
for (int num = 1; num <= 50; ++num) {
if (num % 2 == 0) { // 匹配条件:能被2整除
cout << num << " ";
}
}
return 0;
}
问题描述:
算法解析:
#include <iostream>
#include <cmath>
using namespace std;
int main() {
cout << "1~100之间的所有质数:" << endl;
for (int n = 2; n <= 100; ++n) { // 枚举2~100的候选数
bool isPrime = true;
int limit = sqrt(n); // 预处理:缩小验证范围至√n,优化效率
// 验证是否满足质数条件
for (int i = 2; i <= limit; ++i) {
if (n % i == 0) {
isPrime = false;
break; // 不满足条件,提前终止验证
}
}
if (isPrime) {
cout << n << " ";
}
}
return 0;
}
问题描述:
算法解析:
#include <iostream>
#include <string>
using namespace std;
int main() {
// 小规模字符串数组(解空间)
string nameList[] = {"张三", "李四", "王五", "赵六", "孙七"};
int arrLen = sizeof(nameList) / sizeof(nameList[0]); // 获取数组长度
string targetName = "王五"; // 目标匹配字符串
int targetIndex = -1; // 初始化索引(-1表示未找到)
// 枚举数组元素,逐一匹配
for (int i = 0; i < arrLen; ++i) {
if (nameList[i] == targetName) { // 精确匹配条件
targetIndex = i;
break; // 找到后提前终止枚举,优化效率
}
}
// 输出结果
if (targetIndex != -1) {
cout << "找到目标字符串:" << targetName << ",索引为:" << targetIndex << endl;
} else {
cout << "未找到目标字符串:" << targetName << endl;
}
return 0;
}
问题描述:
算法解析:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
// 小规模字符串集合
vector<string> articleTitles = {
"枚举算法入门教程",
"C++基础语法详解",
"动态规划实战案例",
"算法与数据结构进阶",
"Python爬虫入门"
};
string keyword = "算法"; // 目标子串
cout << "包含关键词\"" << keyword << "\"的标题:" << endl;
// 枚举所有标题,模糊匹配
for (const string& title : articleTitles) {
// 匹配条件:找到子串(返回值不是string::npos)
if (title.find(keyword) != string::npos) {
cout << "- " << title << endl;
}
}
return 0;
}
问题描述:
算法解析:
#include <iostream>
#include <string>
using namespace std;
// 定义学生结构体
struct Student {
string id; // 学号
string name; // 姓名
int score; // 成绩
};
int main() {
// 小规模学生数组
Student students[] = {
{"2025001", "张三", 85},
{"2025002", "李四", 92},
{"2025003", "王五", 88},
{"2025004", "赵六", 95},
{"2025005", "孙七", 79}
};
int studentCount = sizeof(students) / sizeof(students[0]);
cout << "成绩大于90分的优秀学生:" << endl;
// 枚举所有学生,匹配成绩条件
for (int i = 0; i < studentCount; ++i) {
if (students[i].score > 90) { // 匹配条件:成绩>90
cout << "学号:" << students[i].id
<< " 姓名:" << students[i].name
<< " 成绩:" << students[i].score << endl;
}
}
return 0;
}
问题描述:
算法解析:
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector nums = {1, 3, 5, 7, 9, 2, 8}; // 小规模整数数组
int targetSum = 10; // 目标和
cout << "和为" << targetSum << "的元素对:" << endl;
int n = nums.size();
// 双重枚举,避免重复配对(i < j)
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
if (nums[i] + nums[j] == targetSum) { // 匹配条件:和为目标值
cout << "(" << nums[i] << ", " << nums[j] << ")" << endl;
}
}
}
return 0;
}
枚举算法在小规模数据查找与匹配中的实例具有以下共性:
上述实例覆盖了数值、字符串、结构体等多种数据类型,以及精确匹配、模糊匹配、多条件匹配等场景,可直接应用于小规模数据处理场景。