本文共 2963 字,大约阅读时间需要 9 分钟。
在编程过程中,尤其是在使用C++和处理算法时,常常会遇到各种错误。以下是三个常见错误及其解决方案的详细分析,帮助开发者更好地理解问题并找到解决方法。
在Leetcode 102题“二叉树的层序遍历”中使用递归实现时遇到问题。翻译过来,错误信息大致是“引用绑定到了空的指针上”。具体来说,是在处理树节点的左、右子节点时,出现了一个空向量越界的问题。
#includeusing namespace std;class Solution {public: vector levelOrder(TreeNode* root) { vector res; int num = 0; traversal(root, res, num); return res; } void traversal(TreeNode* tree, vector & res, int level) { if (tree == NULL) return; res[level].push_back(tree->val); traversal(tree->left, res, level + 1); traversal(tree->right, res, level + 1); }};
在每次访问res[level]之前,检查当前级别是否超过res的大小,如果超过,则扩容res,添加一个新的空向量。这样可以避免越界问题。
修改后的代码:
#includeusing namespace std;class Solution {public: vector levelOrder(TreeNode* root) { vector res; int num = 0; traversal(root, res, num); return res; } void traversal(TreeNode* tree, vector & res, int level) { if (tree == NULL) return; if (level >= res.size()) { res.push_back(vector ()); } res[level].push_back(tree->val); traversal(tree->left, res, level + 1); traversal(tree->right, res, level + 1); }};
在力扣(剑指offer51)中,在类中对临时数组进行了初始化,但编译器报错,提示“expected parameter declarator”。
class Solution {public: vector tmp(50000, 0); // 这一行报错};
在类中直接写vector
tmp(50000, 0); 会被编译器解释为一个成员函数的声明,而不是对向量的初始化。因为类中的每个成员函数都需要一个参数声明,而这里的语法结构不符合。使用两种方法之一来正确初始化向量:
class Solution {public: vector tmp;};
在类外或构造函数中初始化:
class Solution {public: Solution() { tmp = vector (50000, 0); } vector tmp;};
class Solution {public: vector tmp {50000, 0};};
在类中定义了一个自定义比较函数,然后在类中调用了sort函数,编译器报错,提示“引用到非静态成员函数必须通过对象调用”。
class Solution {public: bool comp(const int& x, const int& y) { // 函数体 } string largestNumber(vector & nums) { sort(intervals.begin(), intervals.end(), cmp); // ... }};
在类中定义了一个非静态成员函数comp,但在调用sort时,传递的是一个函数对象cmp,而不是类的成员函数。由于cmp是非静态成员函数,它需要一个隐式的this指针,而标准库的sort函数不接受this指针,因此会报错。
将比较函数定义为静态成员函数,这样在调用时不需要传递this指针:
class Solution {public: static bool comp(const int& x, const int& y) { // 函数体 } string largestNumber(vector & nums) { sort(intervals.begin(), intervals.end(), comp); // ... }};
通过以上方法,可以避免常见的C++编程错误。记住,在类中定义和使用成员函数时,需要注意静态关键字的使用;在向量扩容时,需要主动检查当前级别是否超过向量的大小,避免越界。
转载地址:http://kuxwz.baihongyu.com/