面试原则:没答好就是不会,不会就去学。
C++中的 map 和 unordered_map 有什么区别?
map 底层数据结构是红黑树(自平衡二叉搜索树),按键的升序自动排序,查找、插入、删除的时间复杂度都是 O(log n);
unordered_map 底层数据结构是哈希表,无序存储,不保证顺序,查找、插入、删除的时间复杂度都是 平均 O(1)、最坏 O(n);
如果不需要有序,优先用 unordered_map(更快);如果需要有序或稳定性能保证,用 map。
C++中有哪些类型转换方式?
C++ 中有 4 种类型转换方式:static_cast、dynamic_cast 、const_cast 、reinterpret_cast。
static_cast - 静态转换:编译时类型转换,用于相关类型之间的转换,不能用于不相关类型的转换(如 int* → double*)。
基本类型转换
类层次中向上转型(安全)
void* 与其他指针类型转换
// 基本类型转换
double d = 3.14;
int i = static_cast<int>(d); // 3
// 类层次中向上转型(安全)
class Base {};
class Derived : public Base {};
Derived d;
Base* b1 = static_cast<Base*>(&d); // 指针
Base& b2 = d; // 引用,隐式转换,推荐使用
Base& b3 = static_cast<Base&>(d); // 引用,显式转换
// void* 与其他指针类型转换
void* p = malloc(100);
int* ip = static_cast<int*>(p);dynamic_cast - 动态转换:运行时类型安全的向下转型,仅用于多态类型(至少有一个虚函数的类)。指针失败返回 nullptr,引用失败抛 bad_cast 异常。
class Base {
public:
virtual ~Base() {} // 必须有虚函数
};
class Derived : public Base {
public:
void derivedOnly() {}
};
Base* b = new Derived();
// 向下转型
Derived* d = dynamic_cast<Derived*>(b);
if (d != nullptr) {
d->derivedOnly(); // 安全调用
}
// 引用转型失败时抛出 bad_cast 异常
Derived& dr = dynamic_cast<Derived&>(*b);const_cast - 常量转换:添加或移除 const / volatile 限定符。(警告:通过 const_cast 修改原本声明为 const 的变量是未定义行为!)
const int a = 10;
int* p = const_cast<int*>(&a); // 去掉 const
void func(int* x) { /* ... */ }
const int b = 20;
func(const_cast<int*>(&b)); // 临时去掉 const 传参reinterpret_cast - 重新解释转换:底层、危险的类型转换,直接重新解释比特位。(警告:高度依赖平台,可移植性差,不到万不得已不要用。)
// 指针与整型互转
int* p = new int(65);
long addr = reinterpret_cast<long>(p); // 指针转整数
int* p2 = reinterpret_cast<int*>(addr); // 整数转指针
// 不相关指针类型互转
int* ip = new int(65);
char* cp = reinterpret_cast<char*>(ip); // 逐字节访问 int
// 函数指针转换
typedef void(*FuncPtr)();
FuncPtr f = reinterpret_cast<FuncPtr>(some_address);Linux中如何动态调整进程的优先级?
通过 nice 和 renice 命令动态调整进程的优先级(实际上是调整"nice值")。
Nice 值范围:-20(最高优先级)到 19(最低优先级)
默认值:0
权限限制:普通用户只能提高 nice 值(降低优先级),只有 root 可以降低 nice 值(提高优先级)
# --- 查看 ---
# 查看当前进程的 nice 值
ps -eo pid,ni,cmd | grep firefox
# --- 设置nice值并运行 ---
# 以 nice 值 10 启动进程(较低优先级)
nice -n 10 ./my_program
# 以最高优先级启动(需要 root)
sudo nice -n -20 ./my_program
# --- 调整 nice 值 ---
# 按 PID 调整
sudo renice -n -5 -p 1234
# 按用户调整(调整该用户所有进程)
sudo renice -n 5 -u username
# 按进程名调整
sudo renice -n 10 -p $(pgrep firefox)
评论区