GESP C++ 6级 2024.09
以下( )没有涉及 C++ 语言的面向对象特性支持。
C++ 中构造一个 或
C++ 中调用 函数
C++ 中调用用户定义的类成员函数
C++ 中构造来源于同一基类的多个派生类
关于以下 C++代码,( )行代码会引起编译错误。
#include
using namespace std;
class Base {
private:
int a;
protected:
int b;
public:
int c;
Base() : a(1), b(2), c(3) {}
};
class Derived : public Base {
public:
void show() {
cout << a << endl; // Line 1
cout << b << endl; // Line 2
cout << c << endl; // Line 3
}
};
有 个元素,按照 的顺序进入栈 ,下列( )的出栈序列是不能出现的
采用如下代码实现检查输入的字符串括号是否匹配,横线上应填入的代码为
#include
#include
#include
using namespace std;
bool is_valid(string s) {
stack st;
char top;
for (char& ch : s) {
if (ch == '(' || ch == '{' || ch == '[') {
st.push(ch); // 左括号入栈
}
else
{
if (st.empty())
return false;
———————————————————————— // 在此处填入代码
if ((ch == ')' && top != '(') ||
(ch == '}' && top != '{') ||
(ch == ']' && top != '[')) {
return false;
}
}
}
return st.empty(); // 栈为空则说明所有括号匹配成功
}
top = st.top(); st.pop();
st.pop(); top = st.top();
st.pop(); top = st.front();
top = st.front(); st.pop();
下面代码判断队列的第一个元素是否等于 ,并删除该元素,横向上应填写
#include
#include
using namespace std;
bool is_front_equal(std::queue& q, int a) {
bool is_equal = false;
if (!q.empty()) {
———————————————————————— // 在此处填入代码
}
return is_equal;
}
is_equal = (q.front() == a);
is_equal = (q.front() == a); q.pop();
q.pop(); is_equal = (q.front() == a);
q.pop(); is_equal = (q.top() == a);
假设字母表 在字符串出现的频率分别为 ,,,,。若使用哈夫曼编码方式对字母进行二进制编码,则字符 分别对应的一组哈夫曼编码的长度分别为( )。
以下C++代码实现 位的格雷码,则横线上应填写
#include
#include
#include
using namespace std;
// 生成 n 位的格雷码
vector generate_graycode(int n) {
vector graycode_list;
if (n = 0; j--) {
graycode_list.push_back("1" + graycode_list[j]);
}
for (int j = 0; j < current_size; j++) {
———————————————————————— // 在此处填入代码
}
}
return graycode_list;
}
graycode_list.push_back("0" + graycode_list[j]);
graycode_list[j] = "0" + graycode_list[j];
graycode_list.push_back("1" + graycode_list[j]);
graycode_list[j] = "1" + graycode_list[j];
给定一棵二叉树,其前序遍历结果为:,中序遍历结果为:,则这棵树的正确后序遍历结果是( )。
一棵有 个结点的完全二叉树用数组进行存储与表示,已知根结点存储在数组的第 个位置。若存储在数组第 个位置的结点存在兄弟结点和两个子结点,则它的兄弟结点和右子结点的位置分别是( )。
二叉树的深度定义为从根结点到叶结点的最长路径上的结点数,则以下基于二叉树的深度优先搜索实现的深度计算函数中横线上应填写
// 定义二叉树的结点结构
struct tree_node {
int val;
tree_node* left;
tree_node* right;
tree_node(int x) : val(x), left(nullptr), right(nullptr) {}
};
// 计算二叉树的深度
int max_depth(tree_node* root) {
if (root == nullptr) {
return 0; // 如果根结点为空,则深度为 0
}
int left_depth = max_depth(root->left);
int right_depth = max_depth(root->right);
———————————————————————— // 在此处填入代码
}
return left_depth + right_depth;
return max(left_depth, right_depth);
return max(left_depth, right_depth) + 1;
return left_depth + right_depth + 1;
