《高质量C++/C编程指南》——林锐博士

需积分: 8 2 下载量 62 浏览量 更新于2024-07-29 收藏 326KB PDF 举报
"《CC++高质量编程》是林锐博士撰写的一本关于C/C++编程的经典书籍,旨在提供高质量的编程指导。书中涵盖了从文件结构、程序版式、命名规则到表达式和基本语句、常量使用、函数设计、内存管理等多个方面的内容,旨在帮助程序员提升代码质量和效率。" 在C++编程中,正确和高效地编写代码至关重要。本书首先介绍了文件结构的相关规范,包括版权和版本声明、头文件的结构、定义文件的结构以及头文件的作用,这些都是构建清晰项目的基础。此外,书中强调了目录结构的重要性,良好的目录结构有助于代码的组织和维护。 程序的版式部分,作者讨论了空行、代码行、空格、对齐、长行拆分、修饰符位置以及注释的使用规范,这些细节直接影响到代码的可读性和团队协作的效率。命名规则章节则涵盖了通用规则,以及针对不同操作系统如Windows和UNIX的应用程序命名规则,以保持代码的一致性和可识别性。 在表达式和基本语句方面,书中分析了运算符的优先级、复合表达式、IF语句、循环语句的效率(特别是FOR语句的循环控制变量)、SWITCH语句以及GOTO语句的使用。这些内容有助于编写更加简洁和高效的控制流程。 关于常量,作者解释了它们的作用,比较了CONST与#DEFINE的区别,并给出了常量定义的规则,同时讨论了在类中使用常量的最佳实践。 函数设计部分探讨了参数规则、返回值规则、函数内部实现的规则,以及如何使用断言来确保代码的正确性。同时,书中比较了引用和指针,帮助开发者理解何时选择哪种类型。 内存管理章节深入剖析了内存分配方式,列举了常见的内存错误及解决策略,区分了指针与数组,详细解释了指针参数如何传递内存,FREE和DELETE操作的影响,动态内存是否自动释放的问题,以及如何避免“野指针”。最后,讨论了MALLOC/FREE和NEW/DELETE的使用场景,以及如何应对内存耗尽的问题。 《CC++高质量编程》是一本全面的C/C++编程指南,旨在提升开发者的编程技能,遵循最佳实践,确保代码的高质量和可维护性。通过阅读此书,开发者可以学习到一系列实用的编程技巧和规范,从而写出更可靠、更易于理解和维护的C++程序。

while any(openSet(:) > 0) % Find the minimum fScore within the open set [~, current] = min(fScore(:)); % If we've reached the goal if current == goal % Get the full path and return it final = get_path(cameFrom, current); return end % Linear index -> row, col subscripts rc = rem(current - 1, mapSize(1)) + 1; cc = (current - rc) / mapSize(1) + 1; % Remove CURRENT from openSet openSet(rc, cc) = false; % Place CURRENT in closedSet closedSet(rc, cc) = true; fScore(rc, cc) = inf; gScoreCurrent = gScore(rc, cc) + costs(rc, cc); % Get all neighbors of CURRENT. Neighbors are adjacent indices on % the map, including diagonals. % Col 1 = Row, Col 2 = Col, Col 3 = Distance to the neighbor n_ss = [ ... rc + 1, cc + 1, S2 ; ... rc + 1, cc + 0, 1 ; ... rc + 1, cc - 1, S2 ; ... rc + 0, cc - 1, 1 ; ... rc - 1, cc - 1, S2 ; ... rc - 1, cc - 0, 1 ; ... rc - 1, cc + 1, S2 ; ... rc - 0, cc + 1, 1 ; ... ]; % keep valid indices only valid_row = n_ss(:,1) >= 1 & n_ss(:,1) <= mapSize(1); valid_col = n_ss(:,2) >= 1 & n_ss(:,2) <= mapSize(2); n_ss = n_ss(valid_row & valid_col, :); % subscripts -> linear indices neighbors = n_ss(:,1) + (n_ss(:,2) - 1) .* mapSize(1); % only keep neighbors in the map and not in the closed set ixInMap = map(neighbors) & ~closedSet(neighbors); neighbors = neighbors(ixInMap); % distance to each kept neighbor dists = n_ss(ixInMap, 3); % Add each neighbor to the open set openSet(neighbors) = true; % TENTATIVE_GSCORE is the score from START to NEIGHBOR. tentative_gscores = gScoreCurrent + costs(neighbors) .* dists; % IXBETTER indicates where a better path was found ixBetter = tentative_gscores < gScore(neighbors); bestNeighbors = neighbors(ixBetter); % For the better paths, update scores cameFrom(bestNeighbors) = current; gScore(bestNeighbors) = tentative_gscores(ixBetter); fScore(bestNeighbors) = gScore(bestNeighbors) + compute_cost(mapSize, bestNeighbors, gr, gc); end % while end

2023-05-25 上传