#if 1 #else if 0 #endif用法 以及pthread的加法

本文介绍了一种使用预编译指令#if1和#if0来控制多线程代码是否被编译的方法,并给出了具体的代码示例。此外还提到了在使用cmakeLists.txt进行编译配置时如何正确地添加-pthread选项。

今天在看程序时,发现一个函数中使用的很多的 

#if 1

......

#endif

#if 0

......

#endif

因为没有用过,感到有点莫名。如是上网查找答案。终于明白是用来注释编译内容的。意思是说:

#if 1    需要编译器编译以下内容;

#if 0   编译器不要编译以下内容;

#if 0   #endif   这种用法还可以实现“注释嵌套!!!”//如果用的话,中间的代码不能加注释。这样不利于调试。

例如:

#include <iostream>
#include <thread>

class Task
{
    public:
    void executeThread(void)
    {
        for(int i = 0; i < 5; i++)
        {
           std::cout << " :: " << i << std::endl;
        }
    }

    void startThread(void);
};

void Task::startThread(void)
{
    std::cout << "\nthis: " << this << std::endl;

#if 1
    std::thread th(&Task::executeThread, this);
    th.join(); // Without this join() or while(1) loop, thread will terminate
    //while(1);
#elif 0
    std::thread(&Task::executeThread, this);  // Thread creation without thread object
#else
    std::thread( std::bind(&Task::executeThread, this) );
    while(1);
#endif
}

int main()
{
    Task* taskPtr = new Task();
    std::cout << "\ntaskPtr: " << taskPtr << std::endl;

    taskPtr->startThread();

    delete taskPtr;
    return 0;
}

构建多线程代码时,在编译和链接时都需要指定-pthread选项。链接器选项-lpthread既不足又不必要。也就是说在使用cmakeLists.txt编写编译信息时,target_link_libraries中添加pthread是链接用的,但是编译的需要加载编译条件里面,也就是和设定C++编译器信息在一起,如-std=c++11 -pthread

 

#include <iostream> #include <string> #include <vector> #include <map> #include <ctime> #include <cstdlib> #include <thread> #include <chrono> #include <algorithm> #include <sstream> #include <memory> #include <functional> #include <cmath> #include <iomanip> #include <fstream> using namespace std; // ============ 智能思考引擎 ============ class DeepThinker { private: bool deepMode; int thinkTime; double accuracy; public: DeepThinker() { srand(time(0)); deepMode = false; thinkTime = 2; accuracy = 0.7; } void enableDeepMode() { deepMode = true; thinkTime = 5; accuracy = 0.9; cout << "?? 深度思考模式已开启!" << endl; cout << "思考时间: " << thinkTime << "秒, 准确率: " << accuracy * 100 << "%" << endl; } void disableDeepMode() { deepMode = false; thinkTime = 2; accuracy = 0.7; cout << "? 快速响应模式已开启!" << endl; } bool isDeepMode() const { return deepMode; } void thinking() const { cout << "?? 思考中"; int dots = deepMode ? 6 : 3; for(int i = 0; i < dots; i++) { cout << "."; cout.flush(); this_thread::sleep_for(chrono::milliseconds(500)); } cout << endl; } double getAccuracy() const { return accuracy + (rand() % 10) / 100.0; } string getResponseType() const { vector<string> types = { "分析型", "创意型", "逻辑型", "批判型", "情感型", "技术型", "哲学型", "实践型" }; return types[rand() % types.size()]; } }; // ============ 情感识别模块 ============ class EmotionRecognizer { private: map<string, vector<string>> emotionKeywords; map<string, int> emotionCount; string toLower(const string& str) { string result = str; transform(result.begin(), result.end(), result.begin(), ::tolower); return result; } vector<string> splitWords(const string& text) { vector<string> words; stringstream ss(text); string word; while(ss >> word) { words.push_back(toLower(word)); } return words; } public: EmotionRecognizer() { // 初始化情感关键词 emotionKeywords["开心"] = {"开心", "高兴", "快乐", "幸福", "喜欢", "爱", "棒", "优秀", "美好", "微笑"}; emotionKeywords["伤心"] = {"伤心", "难过", "悲伤", "痛苦", "哭", "孤独", "寂寞", "失望", "糟糕", "讨厌"}; emotionKeywords["生气"] = {"生气", "愤怒", "恼火", "烦躁", "不爽", "讨厌", "恨", "发火", "暴怒", "气愤"}; emotionKeywords["好奇"] = {"什么", "怎么", "为什么", "何时", "哪里", "哪个", "谁", "解释", "问题", "好奇", "想知道"}; emotionKeywords["平静"] = {"平静", "安宁", "安静", "放松", "冷静", "宁静", "平和", "轻松", "舒适"}; emotionKeywords["困惑"] = {"困惑", "不清楚", "疑惑", "不确定", "迷惑", "茫然", "不懂", "不明白", "混乱"}; emotionKeywords["中性"] = {"中性", "一般", "普通", "还好", "正常", "还行"}; // 初始化情感计数 for(const auto& pair : emotionKeywords) { emotionCount[pair.first] = 0; } } string detectEmotion(const string& text) { vector<string> words = splitWords(text); map<string, int> scores; // 计算每个情感的关键词匹配数 for(const auto& pair : emotionKeywords) { string emotion = pair.first; scores[emotion] = 0; for(const string& keyword : pair.second) { for(const string& word : words) { if(word.find(keyword) != string::npos) { scores[emotion]++; emotionCount[emotion]++; } } } } // 找出最高分的情感 string dominantEmotion = "neutral"; int maxScore = 0; for(const auto& pair : scores) { if(pair.second > maxScore) { maxScore = pair.second; dominantEmotion = pair.first; } } // 如果所有分数都很低,返回中性 if(maxScore == 0) { return "neutral"; } return dominantEmotion; } string getEmoji(const string& emotion) const { map<string, string> emojiMap = { {"开心", "??"}, {"伤心", "??"}, {"生气", "??"}, {"疑惑", "??"}, {"安心", "??"}, {"不满意", "??"}, {"无语", "??"} }; return emojiMap[emotion]; } void showEmotionStats() const { cout << "\n?? 情感统计:" << endl; cout << "==================================" << endl; for(const auto& pair : emotionCount) { if(pair.second > 0) { cout << getEmoji(pair.first) << " " << pair.first << ": " << pair.second << "次" << endl; } } cout << "==================================" << endl; } }; // ============ 知识库系统 ============ class KnowledgeBase { private: map<string, vector<string>> knowledge; map<string, string> facts; map<string, vector<string>> examples; public: KnowledgeBase() { // 数学知识 knowledge["数学"] = { "数学是研究数量、结构、空间和变化的一门学科", "基础运算包括加法、减法、乘法、除法", "几何学研究形状、大小和空间关系", "代数学研究数学符号和运算规则", "微积分研究变化率和累积量" }; // 编程知识 knowledge["编程"] = { "C++是一种通用的编程语言,支持面向对象编程", "变量是存储数据的容器", "函数是执行特定任务的代码块", "循环用于重复执行代码", "条件语句用于根据不同条件执行不同代码" }; // 科学知识 knowledge["科学"] = { "物理学研究物质、能量和它们之间的相互作用", "化学研究物质的组成、性质和变化", "生物学研究生命体和生命过程", "天文学研究天体及其现象", "地球科学研究地球及其过程" }; // 事实数据 facts["pi"] = "3.141592653589793"; facts["e"] = "2.718281828459045"; facts["golden_ratio"] = "1.618033988749895"; facts["light_speed"] = "299792458 m/s"; facts["gravity"] = "9.80665 m/s2"; // 数学示例 examples["加法"] = {"1 + 1 = 2", "2 + 3 = 5", "10 + 15 = 25"}; examples["减法"] = {"5 - 3 = 2", "10 - 4 = 6", "20 - 7 = 13"}; examples["乘法"] = {"2 × 3 = 6", "4 × 5 = 20", "7 × 8 = 56"}; examples["除法"] = {"6 ÷ 2 = 3", "15 ÷ 3 = 5", "24 ÷ 6 = 4"}; } vector<string> getKnowledge(const string& category) const { auto it = knowledge.find(category); if(it != knowledge.end()) { return it->second; } return vector<string>(); } string getFact(const string& key) const { auto it = facts.find(key); if(it != facts.end()) { return it->second; } return "未找到该信息"; } vector<string> getExamples(const string& operation) const { auto it = examples.find(operation); if(it != examples.end()) { return it->second; } return vector<string>(); } bool hasCategory(const string& category) const { return knowledge.find(category) != knowledge.end(); } vector<string> getAllCategories() const { vector<string> categories; for(const auto& pair : knowledge) { categories.push_back(pair.first); } return categories; } void showAllCategories() const { cout << "\n?? 知识库分类:" << endl; cout << "==================================" << endl; for(const auto& category : getAllCategories()) { cout << "? " << category << endl; } cout << "==================================" << endl; } }; // ============ 数学求解器 ============ class MathSolver { private: KnowledgeBase knowledge; double evaluateExpression(const string& expr) { // 简单的表达式求值(仅支持基本运算) size_t plus = expr.find('+'); size_t minus = expr.find('-'); size_t multiply = expr.find('*'); size_t divide = expr.find('/'); if(plus != string::npos) { double a = stod(expr.substr(0, plus)); double b = stod(expr.substr(plus + 1)); return a + b; } else if(minus != string::npos) { double a = stod(expr.substr(0, minus)); double b = stod(expr.substr(minus + 1)); return a - b; } else if(multiply != string::npos) { double a = stod(expr.substr(0, multiply)); double b = stod(expr.substr(multiply + 1)); return a * b; } else if(divide != string::npos) { double a = stod(expr.substr(0, divide)); double b = stod(expr.substr(divide + 1)); if(b != 0) { return a / b; } else { throw runtime_error("除数不能为0"); } } return stod(expr); } public: MathSolver() {} void solveEquation(const string& equation) { cout << "\n?? 解方程: " << equation << endl; cout << "==================================" << endl; try { double result = evaluateExpression(equation); cout << "结果: " << fixed << setprecision(2) << result << endl; // 提供解释 cout << "解释: 这是基本的算术运算。" << endl; } catch(const exception& e) { cout << "错误: " << e.what() << endl; } } void showMathHelp() const { cout << "\n?? 数学帮助:" << endl; cout << "==================================" << endl; cout << "支持的运算:" << endl; cout << "? 加法: a + b" << endl; cout << "? 减法: a - b" << endl; cout << "? 乘法: a * b" << endl; cout << "? 除法: a / b" << endl; cout << "? 平方根: sqrt(x)" << endl; cout << "? 幂运算: a ^ b" << endl; cout << "==================================" << endl; } void showMathFacts() { cout << "\n?? 数学常数:" << endl; cout << "==================================" << endl; cout << "π (pi): " << knowledge.getFact("pi") << endl; cout << "e (自然常数): " << knowledge.getFact("e") << endl; cout << "黄金比例: " << knowledge.getFact("golden_ratio") << endl; cout << "==================================" << endl; } void showExamples(const string& operation) { vector<string> examples = knowledge.getExamples(operation); if(!examples.empty()) { cout << "\n?? " << operation << "示例:" << endl; cout << "==================================" << endl; for(const auto& example : examples) { cout << "? " << example << endl; } cout << "==================================" << endl; } } }; // ============ 对话管理器 ============ class DialogueManager { private: vector<pair<string, string>> conversationHistory; KnowledgeBase knowledge; EmotionRecognizer emotionRecognizer; public: DialogueManager() {} void addMessage(const string& speaker, const string& message) { conversationHistory.push_back(make_pair(speaker, message)); } void showConversation() const { cout << "\n?? 对话历史:" << endl; cout << "==================================" << endl; for(const auto& entry : conversationHistory) { cout << entry.first << ": " << entry.second << endl; } cout << "==================================" << endl; } void clearConversation() { conversationHistory.clear(); cout << "? 对话历史已清空" << endl; } string generateResponse(const string& userInput, const string& emotion) { // 根据用户输入和情感生成回应 vector<string> responses; if(emotion == "开心") { responses = { "听起来很棒!??", "很高兴听到这个!", "这真是个好消息!", "继续保持这样的好心情!" }; } else if(emotion == "难过") { responses = { "我理解你的感受... ??", "如果你需要倾诉,我在这里。", "有时候感到悲伤是正常的。", "希望你能感觉好些。" }; } else if(emotion == "疑惑") { responses = { "这是个很好的问题!??", "让我想想怎么回答...", "我对这个问题很感兴趣。", "这是个值得深入探讨的话题。" }; } else if(emotion == "生气") { responses = { "我理解你的愤怒... ??", "冷静下来,我们可以好好谈谈。", "有时候表达愤怒也是必要的。", "深呼吸,我在这里倾听。" }; } else { responses = { "我明白了。", "有趣的观点。", "继续说,我在听。", "好的,我理解了。" }; } // 随机选择一个回应 srand(time(0)); int index = rand() % responses.size(); // 添加一些智能回复逻辑 if(userInput.find("?") != string::npos) { return responses[index] + " 这是个需要思考的问题。"; } else if(userInput.find("!") != string::npos) { return responses[index] + " 听起来很重要!"; } return responses[index]; } int getConversationLength() const { return conversationHistory.size(); } }; // ============ 学习系统 ============ class LearningSystem { private: map<string, int> userInterests; vector<string> learnedConcepts; int interactionCount; public: LearningSystem() : interactionCount(0) { // 初始化兴趣计数器 userInterests["数学"] = 0; userInterests["科学"] = 0; userInterests["编程"] = 0; userInterests["其它"] = 0; } void recordInteraction(const string& topic) { interactionCount++; // 更新兴趣 if(userInterests.find(topic) != userInterests.end()) { userInterests[topic]++; } else { userInterests["其它"]++; } } void learnConcept(const string& concept) { if(find(learnedConcepts.begin(), learnedConcepts.end(), concept) == learnedConcepts.end()) { learnedConcepts.push_back(concept); cout << "?? 学习了新概念: " << concept << endl; } } string getFavoriteTopic() const { string favorite; int maxCount = 0; for(const auto& pair : userInterests) { if(pair.second > maxCount) { maxCount = pair.second; favorite = pair.first; } } return favorite; } void showLearningStats() const { cout << "\n?? 学习统计:" << endl; cout << "==================================" << endl; cout << "总交互次数: " << interactionCount << endl; cout << "已学概念: " << learnedConcepts.size() << endl; cout << "最感兴趣的主题: " << getFavoriteTopic() << endl; cout << "\n详细兴趣统计:" << endl; for(const auto& pair : userInterests) { if(pair.second > 0) { cout << "? " << pair.first << ": " << pair.second << "次" << endl; } } if(!learnedConcepts.empty()) { cout << "\n已学概念列表:" << endl; for(size_t i = 0; i < min(learnedConcepts.size(), size_t(5)); i++) { cout << "? " << learnedConcepts[i] << endl; } if(learnedConcepts.size() > 5) { cout << "... 等 " << learnedConcepts.size() - 5 << " 个概念" << endl; } } cout << "==================================" << endl; } }; // ============ DeepSeek 3.0 主类 ============ class DeepSeek3 { private: DeepThinker thinker; KnowledgeBase knowledge; MathSolver mathSolver; DialogueManager dialogue; EmotionRecognizer emotionRec; LearningSystem learner; bool running; public: DeepSeek3() : running(true) { cout << "==========================================" << endl; cout << " DeepSeek v3.0测试版 作者张琛" << endl; cout << "==========================================" << endl; cout << "功能特性:" << endl; cout << "? ?? 智能思考引擎" << endl; cout << "? ?? 情感识别系统" << endl; cout << "? ?? 综合知识库" << endl; cout << "? ?? 数学求解器" << endl; cout << "? ?? 对话管理系统" << endl; cout << "? ?? 自适应学习系统" << endl; cout << "==========================================" << endl; } void start() { while(running) { showMainMenu(); int choice; cin >> choice; cin.ignore(); switch(choice) { case 1: startDialogue(); break; case 2: mathMode(); break; case 3: knowledgeMode(); break; case 4: toggleThinkingMode(); break; case 5: showStats(); break; case 6: help(); break; case 7: exitSystem(); break; default: cout << "? 无效选择,请重试" << endl; } } } private: void showMainMenu() { cout << "\n====== DeepSeek v3.0测试版 主菜单 ======" << endl; cout << "当前模式: " << (thinker.isDeepMode() ? "?? 深度思考" : "? 快速响应") << endl; cout << "1. ?? 开始对话" << endl; cout << "2. ?? 数学求解" << endl; cout << "3. ?? 知识查询" << endl; cout << "4. ?? 切换思考模式" << endl; cout << "5. ?? 查看统计" << endl; cout << "6. ? 帮助" << endl; cout << "7. ?? 退出" << endl; cout << "请选择 (1-7): "; } void startDialogue() { cout << "\n?? 对话模式 (输入 'exit' 结束对话)" << endl; cout << "==================================" << endl; string input; while(true) { cout << "\n你: "; getline(cin, input); if(input == "exit") { break; } if(input.empty()) { continue; } // 情感识别 string emotion = emotionRec.detectEmotion(input); string emoji = emotionRec.getEmoji(emotion); cout << "检测到情感: " << emotion << " " << emoji << endl; // 学习系统记录 learner.recordInteraction("general"); // 生成回应 thinker.thinking(); string response = dialogue.generateResponse(input, emotion); cout << "\nDeepSeek: " << response << endl; // 添加到对话历史 dialogue.addMessage("你", input); dialogue.addMessage("DeepSeek", response); // 学习相关概念 if(input.find("数学") != string::npos) { learner.recordInteraction("math"); learner.learnConcept("数学基础"); } else if(input.find("编程") != string::npos || input.find("代码") != string::npos) { learner.recordInteraction("programming"); learner.learnConcept("编程概念"); } else if(input.find("科学") != string::npos) { learner.recordInteraction("science"); learner.learnConcept("科学知识"); } } } void mathMode() { cout << "\n?? 数学求解模式" << endl; cout << "==================================" << endl; mathSolver.showMathHelp(); cout << "\n请输入数学表达式 (如: 3 + 4): "; string expression; getline(cin, expression); if(!expression.empty()) { try { thinker.thinking(); mathSolver.solveEquation(expression); // 记录学习 learner.recordInteraction("math"); learner.learnConcept("数学运算: " + expression); // 询问是否需要更多帮助 cout << "\n是否需要查看更多数学信息?(y/n): "; char choice; cin >> choice; cin.ignore(); if(choice == 'y' || choice == 'Y') { mathSolver.showMathFacts(); cout << "\n查看运算示例:" << endl; cout << "1. 加法示例" << endl; cout << "2. 减法示例" << endl; cout << "3. 乘法示例" << endl; cout << "4. 除法示例" << endl; cout << "请选择 (1-4): "; int exampleChoice; cin >> exampleChoice; cin.ignore(); switch(exampleChoice) { case 1: mathSolver.showExamples("加法"); break; case 2: mathSolver.showExamples("减法"); break; case 3: mathSolver.showExamples("乘法"); break; case 4: mathSolver.showExamples("除法"); break; } } } catch(const exception& e) { cout << "? 错误: " << e.what() << endl; } } } void knowledgeMode() { cout << "\n?? 知识查询模式" << endl; cout << "==================================" << endl; knowledge.showAllCategories(); cout << "\n请选择知识类别 (输入类别名): "; string category; getline(cin, category); if(knowledge.hasCategory(category)) { thinker.thinking(); cout << "\n" << category << "知识:" << endl; cout << "==================================" << endl; vector<string> items = knowledge.getKnowledge(category); for(const auto& item : items) { cout << "? " << item << endl; } cout << "==================================" << endl; // 记录学习 learner.recordInteraction(category); learner.learnConcept("知识类别: " + category); } else { cout << "? 未找到该类别" << endl; } } void toggleThinkingMode() { if(thinker.isDeepMode()) { thinker.disableDeepMode(); } else { thinker.enableDeepMode(); } } void showStats() { cout << "\n?? 系统统计信息" << endl; cout << "==================================" << endl; // 对话统计 cout << "对话轮数: " << dialogue.getConversationLength() << endl; // 情感统计 emotionRec.showEmotionStats(); // 学习统计 learner.showLearningStats(); // 思考模式 cout << "\n当前思考模式: " << (thinker.isDeepMode() ? "深度思考" : "快速响应") << endl; cout << "准确率: " << fixed << setprecision(1) << thinker.getAccuracy() * 100 << "%" << endl; cout << "响应类型: " << thinker.getResponseType() << endl; cout << "==================================" << endl; } void help() { cout << "\n? DeepSeek v3.0测试版 帮助" << endl; cout << "==================================" << endl; cout << "主要功能:" << endl; cout << "1. 对话模式: 进行自然对话,系统会识别你的情感" << endl; cout << "2. 数学求解: 解决基本的数学问题" << endl; cout << "3. 知识查询: 访问预定义的知识库" << endl; cout << "4. 思考模式: 切换深度/快速思考模式" << endl; cout << "5. 系统统计: 查看使用统计和学习进度" << endl; cout << "==================================" << endl; cout << "使用技巧:" << endl; cout << "? 在对话中使用情感词汇会获得更贴切的回应" << endl; cout << "? 深度思考模式下准确率更高但响应较慢" << endl; cout << "? 系统会学习你的兴趣并调整回应" << endl; cout << "==================================" << endl; } void exitSystem() { cout << "\n?? 最终统计报告:" << endl; cout << "==================================" << endl; showStats(); cout << "\n感谢使用 DeepSeek v3.0测试版!" << endl; cout << "期待下次与您对话!" << endl; cout << "再见!??" << endl; running = false; } }; int main() { DeepSeek3 deepseek; deepseek.start(); return 0; } 这是代码,对其进行改错并使其能在 Dev - C++ 中运行
最新发布
12-19
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值