### Hello World 程序结构 Source: https://github.com/learncpp-cn/learncpp-cn.github.io/blob/master/cpp/198adc04/index.html 经典的"Hello world!"程序,展示了C++程序的基本结构,包括预处理指令、main函数、输出语句和返回语句。 ```cpp #include int main() { std::cout << "Hello world!"; return 0; } ``` -------------------------------- ### Project Configuration and Tracking Source: https://github.com/learncpp-cn/learncpp-cn.github.io/blob/master/archives/index.html This snippet contains JavaScript code for configuring the NexT theme, including sidebar settings, animations, and search integration with Algolia. It also includes Google Analytics tracking. ```javascript var NexT = window.NexT || {}; var CONFIG = { root: '/', scheme: 'Pisces', version: '6.7.0', sidebar: {"position":"left","b2t":true,"scrollpercent":true}, fancybox: false, fastclick: false, lazyload: false, tabs: true, motion: {"enable":true,"async":false,"transition":{ "post_block":"fadeIn", "post_header":"slideDownIn", "post_body":"slideDownIn", "coll_header":"slideLeftIn", "sidebar":"slideUpIn" }}, algolia: { applicationID: '', apiKey: '', indexName: '', hits: {"per_page":10}, labels: { "input_placeholder": "Search for Posts", "hits_empty": "We didn't find any results for the search: ${query}", "hits_stats": "${hits} results found in ${time} ms" } } }; CONFIG.page = { sidebar: "" }; window.dataLayer = window.dataLayer || []; function gtag(){ dataLayer.push(arguments); } gtag('js', new Date()); gtag('config', 'UA-82042025-2'); ``` -------------------------------- ### Project Configuration and Tracking Source: https://github.com/learncpp-cn/learncpp-cn.github.io/blob/master/archives/2019/index.html This snippet contains JavaScript code for configuring the NexT theme, including sidebar settings, animations, and search integration with Algolia. It also includes Google Analytics tracking. ```javascript var NexT = window.NexT || {}; var CONFIG = { root: '/', scheme: 'Pisces', version: '6.7.0', sidebar: {"position":"left","b2t":true,"scrollpercent":true}, fancybox: false, fastclick: false, lazyload: false, tabs: true, motion: {"enable":true,"async":false,"transition":{ "post_block":"fadeIn", "post_header":"slideDownIn", "post_body":"slideDownIn", "coll_header":"slideLeftIn", "sidebar":"slideUpIn" }}, algolia: { applicationID: '', apiKey: '', indexName: '', hits: {"per_page":10}, labels: { "input_placeholder": "Search for Posts", "hits_empty": "We didn't find any results for the search: ${query}", "hits_stats": "${hits} results found in ${time} ms" } } }; CONFIG.page = { sidebar: "" }; window.dataLayer = window.dataLayer || []; function gtag(){ dataLayer.push(arguments); } gtag('js', new Date()); gtag('config', 'UA-82042025-2'); ``` -------------------------------- ### Project Configuration and Tracking Source: https://github.com/learncpp-cn/learncpp-cn.github.io/blob/master/archives/2019/04/index.html This snippet contains JavaScript code for configuring the NexT theme, including sidebar settings, animations, and search integration with Algolia. It also includes Google Analytics tracking. ```javascript var NexT = window.NexT || {}; var CONFIG = { root: '/', scheme: 'Pisces', version: '6.7.0', sidebar: {"position":"left","b2t":true,"scrollpercent":true}, fancybox: false, fastclick: false, lazyload: false, tabs: true, motion: {"enable":true,"async":false,"transition":{ "post_block":"fadeIn", "post_header":"slideDownIn", "post_body":"slideDownIn", "coll_header":"slideLeftIn", "sidebar":"slideUpIn" }}, algolia: { applicationID: '', apiKey: '', indexName: '', hits: {"per_page":10}, labels: { "input_placeholder": "Search for Posts", "hits_empty": "We didn't find any results for the search: ${query}", "hits_stats": "${hits} results found in ${time} ms" } } }; CONFIG.page = { sidebar: "" }; window.dataLayer = window.dataLayer || []; function gtag(){ dataLayer.push(arguments); } gtag('js', new Date()); gtag('config', 'UA-82042025-2'); ``` -------------------------------- ### C++ Hello World示例 Source: https://github.com/learncpp-cn/learncpp-cn.github.io/blob/master/cpp/46108864/index.html 一个基础的C++程序,用于在控制台输出“Colored text!”。此示例展示了C++的基本结构,包括包含头文件和main函数。 ```C++ #include int main() { std::cout << "Colored text!"; return 0; } ``` -------------------------------- ### C++ Hello World 示例(带语法错误) Source: https://github.com/learncpp-cn/learncpp-cn.github.io/blob/master/cpp/198adc04/index.html 这是一个C++的“Hello World”程序,其中故意省略了第5行末尾的分号,以演示一个常见的语法错误。编译器会报告此错误,指示在`return 0;`语句之前缺少分号。 ```cpp #include int main() { std::cout << "Hello world!" return 0; } ``` -------------------------------- ### C++ 链接过程说明 Source: https://github.com/learncpp-cn/learncpp-cn.github.io/blob/master/cpp/9b6d5a68/index.html 这段文字解释了链接器的作用。链接器将编译器生成的所有目标文件组合成一个可执行程序,并链接库文件(如C++标准库)。它还负责解析跨文件依赖关系,并在出现问题时报告链接器错误。 ```text 首先,获取编译器生成的所有目标文件,并将它们组合成一个可执行程序。 其次,除了能够链接目标文件之外,链接器还能够链接库文件。一个库文件是预编译代码的集合,它已经“打包”在其他程序中重用。 第三,链接器确保正确解析所有跨文件依赖关系。例如,如果您在一个.cpp文件中定义某个内容,然后在另一个.cpp文件中使用它,则链接器会将两者连接在一起。如果链接器无法使用该事物的定义连接对事物的引用,则会出现链接器错误,并且链接过程将中止。 ``` -------------------------------- ### Code::Blocks 安装 MinGW 指南 Source: https://github.com/learncpp-cn/learncpp-cn.github.io/blob/master/cpp/fd9ffcf1/index.html 指导Windows用户下载并安装捆绑了MinGW(GCC C++编译器的Windows端口)的Code::Blocks版本,以确保编译器可用。 ```markdown ### Code :: Blocks(适用于Linux或Windows) 如果您正在使用Linux进行开发(或者您正在开发Windows但希望编写可以轻松移植到Linux的程序),我们建议使用Code :: Blocks。Code :: Blocks是一个免费的开源跨平台IDE,可以在Linux和Windows上运行。 > 对于Windows用户 > > 确保获得捆绑了MinGW的Code :: Blocks的版本(它应该是其文件名以mingw-setup.exe结尾的版本)。这将安装MinGW,其中包括GCC C++编译器的Windows端口: ![Code :: Blocks MinGW Windows下载](https://www.learncpp.com/images/CppTutorial/Chapter0/CB-MinGWDownload-min.png) 当您第一次启动Code :: Blocks时,您可能会得到一个编译器自动检测对话框。如果这样做,请确保将GNU GCC Compiler设置为默认编译器,然后选择确定按钮。 ![编译器自动检测对话框](https://www.learncpp.com/images/CppTutorial/Chapter0/CompilersAutoDetection-min.png) ``` -------------------------------- ### Local Search Initialization and Event Handling Source: https://github.com/learncpp-cn/learncpp-cn.github.io/blob/master/cpp/9783892c/index.html Initializes the search functionality, sets up event listeners for the search input, and handles the display of search results. It also manages the popup window and overlay for the search interface. ```javascript if (Object.prototype.toString.call(window.Promise) !== '[object Function]') { window.Promise = null; } // Popup Window; var isfetched = false; var isXml = true; // Search DB path; var search_path = "search.xml"; if (search_path.length === 0) { search_path = "search.xml"; } else if (/json$/i.test(search_path)) { isXml = false; } var path = "/" + search_path; // monitor main search box; var onPopupClose = function (e) { $('.popup').hide(); $('#local-search-input').val(''); $('.search-result-list').remove(); $('#no-result').remove(); $(".local-search-pop-overlay").remove(); $('body').css('overflow', ''); } function proceedsearch() { $("body") .append('
') .css('overflow', 'hidden'); $('.search-popup-overlay').click(onPopupClose); $('.popup').toggle(); var $localSearchInput = $('#local-search-input'); $localSearchInput.attr("autocapitalize", "none"); $localSearchInput.attr("autocorrect", "off"); $localSearchInput.focus(); } ``` -------------------------------- ### Visual Studio 语法错误报告 Source: https://github.com/learncpp-cn/learncpp-cn.github.io/blob/master/cpp/198adc04/index.html 当编译包含语法错误的C++代码时,Visual Studio会生成类似这样的错误消息。该消息指出了错误发生的行号以及具体的错误类型(缺少分号)。 ```text c:\vcprojects\test1.cpp(6): error C2143: syntax error : missing ';' before 'return' ``` -------------------------------- ### 网站导航链接 Source: https://github.com/learncpp-cn/learncpp-cn.github.io/blob/master/archives/2019/02/index.html 这段HTML代码定义了网站的主要导航链接,包括指向首页、归档页和搜索功能的链接,以及一个GitHub关注链接。 ```html [LearnCpp中文版](/) C++教程 在线文档 ========== * [ 首页](/) * [ 归档](/archives/) * [ 搜索](javascript:;) [](https://github.com/luochuanyuewu "在github上关注我") ``` -------------------------------- ### Local Search Initialization and Event Handling Source: https://github.com/learncpp-cn/learncpp-cn.github.io/blob/master/cpp/f10c6aa3/index.html Initializes the search functionality, sets up event listeners for the search input, and handles the display of search results. It also manages the popup window and overlay for the search interface. ```javascript if (Object.prototype.toString.call(window.Promise) !== '[object Function]') { window.Promise = null; } // Popup Window; var isfetched = false; var isXml = true; // Search DB path; var search_path = "search.xml"; if (search_path.length === 0) { search_path = "search.xml"; } else if (/json$/i.test(search_path)) { isXml = false; } var path = "/" + search_path; // monitor main search box; var onPopupClose = function (e) { $('.popup').hide(); $('#local-search-input').val(''); $('.search-result-list').remove(); $('#no-result').remove(); $(".local-search-pop-overlay").remove(); $('body').css('overflow', ''); } function proceedsearch() { $("body") .append('
') .css('overflow', 'hidden'); $('.search-popup-overlay').click(onPopupClose); $('.popup').toggle(); var $localSearchInput = $('#local-search-input'); $localSearchInput.attr("autocapitalize", "none"); $localSearchInput.attr("autocorrect", "off"); $localSearchInput.focus(); } ``` -------------------------------- ### Promise Polyfill and Local Search Initialization Source: https://github.com/learncpp-cn/learncpp-cn.github.io/blob/master/archives/2019/02/index.html This snippet checks if the browser's Promise implementation is valid and sets it to null if not. It also initializes variables for the local search functionality, determining the path to the search data (XML or JSON) and setting up event handlers for the search popup. ```javascript if (Object.prototype.toString.call(window.Promise) !== '\includegraphics[width=0.8em]{{'/icons/promise.png'}}') { window.Promise = null; } // Popup Window; var isfetched = false; var isXml = true; // Search DB path; var search_path = "search.xml"; if (search_path.length === 0) { search_path = "search.xml"; } else if (/json$/i.test(search_path)) { isXml = false; } var path = "/" + search_path; // monitor main search box; var onPopupClose = function (e) { $('.popup').hide(); $('#local-search-input').val(''); $('.search-result-list').remove(); $('#no-result').remove(); $(".local-search-pop-overlay").remove(); $('body').css('overflow', ''); } function proceedsearch() { $("body") .append('
') .css('overflow', 'hidden'); $('.search-popup-overlay').click(onPopupClose); $('.popup').toggle(); var $localSearchInput = $('#local-search-input'); $localSearchInput.attr("autocapitalize", "none"); $localSearchInput.attr("autocorrect", "off"); $localSearchInput.focus(); } ``` -------------------------------- ### 网站导航链接 Source: https://github.com/learncpp-cn/learncpp-cn.github.io/blob/master/archives/2019/04/page/2/index.html 这段HTML代码定义了网站的主要导航链接,包括指向首页、归档页和搜索功能的链接,以及一个GitHub关注链接。 ```html [LearnCpp中文版](/) C++教程 在线文档 ========== * [ 首页](/) * [ 归档](/archives/) * [ 搜索](javascript:;) [](https://github.com/luochuanyuewu "在github上关注我") ``` -------------------------------- ### 网站导航链接 Source: https://github.com/learncpp-cn/learncpp-cn.github.io/blob/master/cpp/1ed2d910/index.html 这段HTML代码定义了网站的导航链接,包括指向首页的链接以及一个用于触发搜索功能的链接。它还包含一个指向GitHub的链接,用于关注作者。 ```html [LearnCpp中文版](/) C++教程 在线文档 ========== * [ 首页](/) * [ 归档](/archives/) * [ 搜索](javascript:;) [](https://github.com/luochuanyuewu "在github上关注我") ``` -------------------------------- ### Code::Blocks 编译器未找到错误排查 Source: https://github.com/learncpp-cn/learncpp-cn.github.io/blob/master/cpp/fd9ffcf1/index.html 提供了解决Code::Blocks中“在GNU GCC编译器的已配置搜索路径中找不到编译器可执行文件”错误的步骤,包括检查MinGW安装、重置默认设置和重新安装。 ```markdown 问:我收到“在GNU GCC编译器的已配置搜索路径中找不到编译器可执行文件”错误 请尝试以下方法: 1. 在Windows上,请确保已下载Code :: Blocks WITH MinGW的版本。这是名字中有“mingw”的人。 2. 尝试进入设置,编译器,然后选择“重置为默认值”。 3. 尝试转到设置,编译器,工具链可执行文件选项卡,并确保将“编译器的安装目录”设置为MinGW目录(例如C:\ Program Files(x86)\ CodeBlocks \ MinGW)。 4. 尝试执行完全卸载,然后重新安装。 5. 尝试不同的编译器。 ``` -------------------------------- ### C++ 基础程序结构 Source: https://github.com/learncpp-cn/learncpp-cn.github.io/blob/master/cpp/71fb958f/index.html 提供了一个基本的C++程序框架,用于编译代码片段。它包含了必要的头文件包含和main函数结构。 ```cpp #include int main() { // Replace this line with the snippet of code you'd like to compile return 0; } ``` -------------------------------- ### Visual Studio Community 2017 安装指南 Source: https://github.com/learncpp-cn/learncpp-cn.github.io/blob/master/cpp/fd9ffcf1/index.html 指导用户在Windows上安装Visual Studio Community 2017,重点是选择“使用C++进行桌面开发”工作负载,并确保安装Windows 10 SDK。 ```markdown ### Visual Studio(适用于Windows) 如果您在Windows机器上进行开发(大多数人都是如此)并且磁盘空间和下载大小不是约束,那么我们强烈建议您使用Visual Studio Community 2017。当您运行安装程序时,您最终会进入一个屏幕,询问您要安装的工作负载。选择使用C++进行桌面开发。如果不这样做,那么C++功能将无法使用。 在屏幕右侧选择的默认选项应该没问题,但请确保选择了Windows 10 SDK。Windows 10 SDK可以在旧版本的Windows上使用,因此如果您仍在运行Windows 7或8,请不要担心。 ![Visual Studio工作负载](https://www.learncpp.com/images/CppTutorial/Chapter0/VS2017-Installer-min.png) 如果磁盘空间和/或下载大小是一个挑战,那么我们建议使用Microsoft免费的Windows桌面Visual Studio Express 2017,您可以在页面底部找到它。 ``` -------------------------------- ### 命名变量作为左值 Source: https://github.com/learncpp-cn/learncpp-cn.github.io/blob/master/cpp/96d9fb0d/index.html 说明即使变量被声明为右值引用,它本身仍然是一个左值。因此,将一个右值引用的变量传递给期望右值引用的函数时,会调用左值版本的函数。 ```cpp #include void fun(const int &lref) // l-value arguments will select this function { std::cout << "l-value reference to const\n"; } void fun(int &&rref) // r-value arguments will select this function { std::cout << "r-value reference\n"; } int main() { int &&ref = 5; fun(ref); // l-value argument calls l-value version of function return 0; } ``` -------------------------------- ### 本地搜索功能实现 Source: https://github.com/learncpp-cn/learncpp-cn.github.io/blob/master/cpp/9b6d5a68/index.html 实现了网站的本地搜索功能,允许用户输入关键词并在搜索结果中查找匹配的文章。该功能支持XML或JSON格式的搜索数据,并对搜索结果进行高亮显示。 ```JavaScript if (Object.prototype.toString.call(window.Promise) !== '["object Function"]') { window.Promise = null; } // Popup Window; var isfetched = false; var isXml = true; // Search DB path; var search_path = "search.xml"; if (search_path.length === 0) { search_path = "search.xml"; } else if (/json$/i.test(search_path)) { isXml = false; } var path = "/" + search_path; // monitor main search box; var onPopupClose = function (e) { $('.popup').hide(); $('#local-search-input').val(''); $('.search-result-list').remove(); $('#no-result').remove(); $(".local-search-pop-overlay").remove(); $('body').css('overflow', ''); } function proceedsearch() { $("body") .append('
') .css('overflow', 'hidden'); $('.search-popup-overlay').click(onPopupClose); $('.popup').toggle(); var $localSearchInput = $('#local-search-input'); $localSearchInput.attr("autocapitalize", "none"); $localSearchInput.attr("autocorrect", "off"); $localSearchInput.focus(); } // search function; var searchFunc = function(path, search_id, content_id) { 'use strict'; // start loading animation $("body") .append('
' + '
' + '' + '
' + '
') .css('overflow', 'hidden'); $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center'); $.ajax({ url: path, dataType: isXml ? "xml" : "json", async: true, success: function(res) { // get the contents from search data isfetched = true; $('.popup').detach().appendTo('.header-inner'); var datas = isXml ? $("entry", res).map(function() { return { title: $("title", this).text(), content: $("content",this).text(), url: $("url" , this).text() }; }).get() : res; var input = document.getElementById(search_id); var resultContent = document.getElementById(content_id); var inputEventFunction = function() { var searchText = input.value.trim().toLowerCase(); var keywords = searchText.split(/["\s\-]+/); if (keywords.length > 1) { keywords.push(searchText); } var resultItems = []; if (searchText.length > 0) { // perform local searching datas.forEach(function(data) { var isMatch = false; var hitCount = 0; var searchTextCount = 0; var title = data.title.trim(); var titleInLowerCase = title.toLowerCase(); var content = data.content.trim().replace(/<[^>]+>/g,""); var contentInLowerCase = content.toLowerCase(); var articleUrl = decodeURIComponent(data.url).replace(/\/{2,}/g, '/'); var indexOfTitle = []; var indexOfContent = []; // only match articles with not empty titles if(title != '') { keywords.forEach(function(keyword) { function getIndexByWord(word, text, caseSensitive) { var wordLen = word.length; if (wordLen === 0) { return []; } var startPosition = 0, position = [], index = []; if (!caseSensitive) { text = text.toLowerCase(); word = word.toLowerCase(); } while ((position = text.indexOf(word, startPosition)) > -1) { index.push({position: position, word: word}); startPosition = position + wordLen; } return index; } indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false)); indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false)); }); if (indexOfTitle.length > 0 || indexOfContent.length > 0) { isMatch = true; hitCount = indexOfTitle.length + indexOfContent.length; } } // show search results if (isMatch) { // sort index by position of keyword [indexOfTitle, indexOfContent].forEach(function (index) { index.sort(function (itemLeft, itemRight) { if (itemRight.position !== itemLeft.position) { return itemRight.position - itemLeft.position; } else { return itemLeft.word.length - itemRight.word.length; } }); }); // merge hits into slices function mergeIntoSlice(text, start, end, index) { var item = index[index.length - 1]; var position = item.position; var word = item.word; var hits = []; var searchTextCountInSlice = 0; while (position + word.length <= end && index.length != 0) { if (word === searchText) { searchTextCountInSlice++; } hits.push({position: ``` -------------------------------- ### 本地搜索功能 Source: https://github.com/learncpp-cn/learncpp-cn.github.io/blob/master/archives/page/2/index.html 此JavaScript函数实现了网站的本地搜索功能。它使用AJAX加载搜索数据(XML或JSON格式),并在用户输入时过滤和显示匹配的文章。该函数处理搜索框的输入事件,高亮显示匹配的文本,并提供加载和无结果的视觉反馈。 ```javascript var isfetched = false; var isXml = true; var search_path = "search.xml"; if (search_path.length === 0) { search_path = "search.xml"; } else if (/json$/i.test(search_path)) { isXml = false; } var path = "/" + search_path; var onPopupClose = function (e) { $('.popup').hide(); $('#local-search-input').val(''); $('.search-result-list').remove(); $('#no-result').remove(); $(".local-search-pop-overlay").remove(); $('body').css('overflow', ''); } function proceedsearch() { $("body") .append('
') .css('overflow', 'hidden'); $('.search-popup-overlay').click(onPopupClose); $('.popup').toggle(); var $localSearchInput = $('#local-search-input'); $localSearchInput.attr("autocapitalize", "none"); $localSearchInput.attr("autocorrect", "off"); $localSearchInput.focus(); } var searchFunc = function(path, search_id, content_id) { 'use strict'; $("body") .append('
' + '
' + '' + '
' + '
') .css('overflow', 'hidden'); $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center'); $.ajax({ url: path, dataType: isXml ? "xml" : "json", async: true, success: function(res) { isfetched = true; $('.popup').detach().appendTo('.header-inner'); var datas = isXml ? $("entry", res).map(function() { return { title: $("title", this).text(), content: $("content",this).text(), url: $("url" , this).text() }; }).get() : res; var input = document.getElementById(search_id); var resultContent = document.getElementById(content_id); var inputEventFunction = function() { var searchText = input.value.trim().toLowerCase(); var keywords = searchText.split(/[\\s\\-\]+/); if (keywords.length > 1) { keywords.push(searchText); } var resultItems = []; if (searchText.length > 0) { datas.forEach(function(data) { var isMatch = false; var hitCount = 0; var searchTextCount = 0; var title = data.title.trim(); var titleInLowerCase = title.toLowerCase(); var content = data.content.trim().replace(/<[^>]+>/g,""); var contentInLowerCase = content.toLowerCase(); var articleUrl = decodeURIComponent(data.url).replace(/\/{2,}/g, '/'); var indexOfTitle = []; var indexOfContent = []; if(title != '') { keywords.forEach(function(keyword) { function getIndexByWord(word, text, caseSensitive) { var wordLen = word.length; if (wordLen === 0) { return []; } var startPosition = 0, position = [], index = []; if (!caseSensitive) { text = text.toLowerCase(); word = word.toLowerCase(); } while ((position = text.indexOf(word, startPosition)) > -1) { index.push({position: position, word: word}); startPosition = position + wordLen; } return index; } indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false)); indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false)); }); if (indexOfTitle.length > 0 || indexOfContent.length > 0) { isMatch = true; hitCount = indexOfTitle.length + indexOfContent.length; } } if (isMatch) { [indexOfTitle, indexOfContent].forEach(function (index) { index.sort(function (itemLeft, itemRight) { if (itemRight.position !== itemLeft.position) { return itemRight.position - itemLeft.position; } else { return itemLeft.word.length - itemRight.word.length; } }); }); function mergeIntoSlice(text, start, end, index) { var item = index[index.length - 1]; var position = item.position; var word = item.word; var hits = []; var searchTextCountInSlice = 0; while (position + word.length <= end && index.length != 0) { if (word === searchText) { searchTextCountInSlice++; } hits.push({position: position, length: word.length}); var wordEnd = position + word.length; index.pop(); while (index.length != 0) { item = index[index.length - 1]; position = item.position; word = item.word; if (wordEnd > position) { index.pop(); } else { break; } } } searchTextCount += searchTextCountInSlice; return { hits: hits, start: start, end: end, searc ``` -------------------------------- ### 本地搜索功能实现 Source: https://github.com/learncpp-cn/learncpp-cn.github.io/blob/master/cpp/96d9fb0d/index.html 该代码块实现了本地搜索功能,包括搜索框的输入处理、数据匹配和结果显示。它支持XML或JSON格式的搜索数据,并提供加载动画和结果列表的动态更新。 ```javascript var isfetched = false; var isXml = true; var search_path = "search.xml"; if (search_path.length === 0) { search_path = "search.xml"; } else if (/json$/i.test(search_path)) { isXml = false; } var path = "/" + search_path; var onPopupClose = function (e) { $('.popup').hide(); $('#local-search-input').val(''); $('.search-result-list').remove(); $('#no-result').remove(); $(".local-search-pop-overlay").remove(); $('body').css('overflow', ''); } function proceedsearch() { $("body") .append('
') .css('overflow', 'hidden'); $('.search-popup-overlay').click(onPopupClose); $('.popup').toggle(); var $localSearchInput = $('#local-search-input'); $localSearchInput.attr("autocapitalize", "none"); $localSearchInput.attr("autocorrect", "off"); $localSearchInput.focus(); } var searchFunc = function(path, search_id, content_id) { 'use strict'; $("body") .append('
' + '
' + '' + '
' + '
') .css('overflow', 'hidden'); $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center'); $.ajax({ url: path, dataType: isXml ? "xml" : "json", async: true, success: function(res) { isfetched = true; $('.popup').detach().appendTo('.header-inner'); var datas = isXml ? $("entry", res).map(function() { return { title: $("title", this).text(), content: $("content", this).text(), url: $("url", this).text() }; }).get() : res; var input = document.getElementById(search_id); var resultContent = document.getElementById(content_id); var inputEventFunction = function() { var searchText = input.value.trim().toLowerCase(); var keywords = searchText.split(/[\\s\\-\]+/); if (keywords.length > 1) { keywords.push(searchText); } var resultItems = []; if (searchText.length > 0) { datas.forEach(function(data) { var isMatch = false; var hitCount = 0; var searchTextCount = 0; var title = data.title.trim(); var titleInLowerCase = title.toLowerCase(); var content = data.content.trim().replace(/<[^>]+>/g, ""); var contentInLowerCase = content.toLowerCase(); var articleUrl = decodeURIComponent(data.url).replace(/\/{2,}/g, '/'); var indexOfTitle = []; var indexOfContent = []; if (title != '') { keywords.forEach(function(keyword) { function getIndexByWord(word, text, caseSensitive) { var wordLen = word.length; if (wordLen === 0) { return []; } var startPosition = 0, position = [], index = []; if (!caseSensitive) { text = text.toLowerCase(); word = word.toLowerCase(); } while ((position = text.indexOf(word, startPosition)) > -1) { index.push({position: position, word: word}); startPosition = position + wordLen; } return index; } indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false)); indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false)); }); if (indexOfTitle.length > 0 || indexOfContent.length > 0) { isMatch = true; hitCount = indexOfTitle.length + indexOfContent.length; } } if (isMatch) { [indexOfTitle, indexOfContent].forEach(function (index) { index.sort(function (itemLeft, itemRight) { if (itemRight.position !== itemLeft.position) { return itemRight.position - itemLeft.position; } else { return itemLeft.word.length - itemRight.word.length; } }); }); function mergeIntoSlice(text, start, end, index) { var item = index[index.length - 1]; var position = item.position; var word = item.word; var hits = []; var searchTextCountInSlice = 0; while (position + word.length <= end && index.length != 0) { if (word === searchText) { searchTextCountInSlice++; } hits.push({position: position, length: word.length}); var wordEnd = position + word.length; index.pop(); while (index ``` -------------------------------- ### 本地搜索功能实现 Source: https://github.com/learncpp-cn/learncpp-cn.github.io/blob/master/cpp/1ef7169f/index.html 这是一个JavaScript代码片段,用于实现本地搜索功能,包括搜索框的输入处理、数据匹配和结果显示。它还包含了搜索加载动画和弹出窗口的管理。 ```javascript if (Object.prototype.toString.call(window.Promise) !== '[object Function]') { window.Promise = null; } var isfetched = false; var isXml = true; var search_path = "search.xml"; if (search_path.length === 0) { search_path = "search.xml"; } else if (/json$/i.test(search_path)) { isXml = false; } var path = "/" + search_path; var onPopupClose = function (e) { $('.popup').hide(); $('#local-search-input').val(''); $('.search-result-list').remove(); $('#no-result').remove(); $(".local-search-pop-overlay").remove(); $('body').css('overflow', ''); } function proceedsearch() { $("body") .append('
') .css('overflow', 'hidden'); $('.search-popup-overlay').click(onPopupClose); $('.popup').toggle(); var $localSearchInput = $('#local-search-input'); $localSearchInput.attr("autocapitalize", "none"); $localSearchInput.attr("autocorrect", "off"); $localSearchInput.focus(); } var searchFunc = function(path, search_id, content_id) { 'use strict'; $("body") .append('
' + '
' + '' + '
' + '
') .css('overflow', 'hidden'); $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center'); $.ajax({ url: path, dataType: isXml ? "xml" : "json", async: true, success: function(res) { isfetched = true; $('.popup').detach().appendTo('.header-inner'); var datas = isXml ? $("entry", res).map(function() { return { title: $("title", this).text(), content: $("content", this).text(), url: $("url", this).text() }; }).get() : res; var input = document.getElementById(search_id); var resultContent = document.getElementById(content_id); var inputEventFunction = function() { var searchText = input.value.trim().toLowerCase(); var keywords = searchText.split(/[\\s\\-\]+/); if (keywords.length > 1) { keywords.push(searchText); } var resultItems = []; if (searchText.length > 0) { datas.forEach(function(data) { var isMatch = false; var hitCount = 0; var searchTextCount = 0; var title = data.title.trim(); var titleInLowerCase = title.toLowerCase(); var content = data.content.trim().replace(/<[^>]+>/g, ""); var contentInLowerCase = content.toLowerCase(); var articleUrl = decodeURIComponent(data.url).replace(/\/{2,}/g, '/'); var indexOfTitle = []; var indexOfContent = []; if (title != '') { keywords.forEach(function(keyword) { function getIndexByWord(word, text, caseSensitive) { var wordLen = word.length; if (wordLen === 0) { return []; } var startPosition = 0, position = [], index = []; if (!caseSensitive) { text = text.toLowerCase(); word = word.toLowerCase(); } while ((position = text.indexOf(word, startPosition)) > -1) { index.push({ position: position, word: word }); startPosition = position + wordLen; } return index; } indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false)); indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false)); }); if (indexOfTitle.length > 0 || indexOfContent.length > 0) { isMatch = true; hitCount = indexOfTitle.len ```