尧图精选

【C++】 string 类补充知识

🕒 发布时间:2026/10/2 13:46:02 📁 来源:尧图网络
1. 运算符重载swap传统写法的特点先判断自赋值 → 开空间 → 拷贝数据的版本直观易懂逻辑线性和拷贝构造思路接近适合应试手写一眼看懂每一步操作。内存开销可控只分配目标大小内存不会额外创建临时对象内存占用少。性能较好没有额外拷贝直接在当前对象空间复用reserve 容量足够时不重新开堆。//传统写法 string string::operator (const string str) { if (this str) { return; } delete[] _str; char* tmp new char[str.capacity() 1]; memcpy(tmp, str._str, str._size 1); _str tmp; _capacity str._capacity; _size str._size; return *this; } string string::operator (const char c) { delete[] _str; char* tmp new char[2] {c, 0}; _size 1; _str tmp; _capacity 1; return *this; } string string::operator (const char* s) { size_t size strlen(s); delete[] _str; char* tmp new char[size 1]; memcpy(tmp, s, size 1); _size size; _capacity size; return *this; }现代写法特点核心原理形参值传递调用拷贝构造生成临时对象然后 swap 交换*this和临时对象的内部资源函数结束临时对象析构带走旧资源。// string 类的 swap void string::swap(string str) { std::swap(_str, str._str); std::swap(_size, str._size); std::swap(_capacity, str._capacity); } //现代写法 string string::operator (const string str) { if(this ! str) { string tmp str; swap(tmp); } return *this; // 注意 str 在该函数 就会自动调用 ~string 销毁 } // 更简洁版 string string::operator (string str) { swap(str); return *this; // 注意 str 在该函数 就会自动调用 ~string 销毁 }问题一为什么还需要单独给 string 作一个 swap 的适配直接调用std 标准库内的swap 需要调用拷贝构造函数申请空间所需时间比较浪费。如果只是对齐对应的地址很复制进行拷贝就无需申请空间减少不必要的时间浪费。2. string的所占内存大小string 类的成员变量一个 char* 和 两个 size_t 按理来说是输出12x86但实际标准库内输出string所占的内存空间是28。而这个多出来的16字符是来自于这里的空间换时间多的空间换来时间更快速的响应在小于16字符的字符串就可以无需申请空间直接使用现成的16字符空间插入 _Buf3stoi 整型转字符stoi 函数简介stoi 是 C 标准库string中提供的字符串转整型函数用于把字符串按指定进制解析为 int 类型。它的函数原型如下int stoi(const string str, size_t* pos 0, int base 10);其中base参数用于指定进制支持 2、8、10、16 等常见进制。当base为 0 时编译器会根据字符串前缀自动判断进制0x 开头按 16 进制0 开头按 8 进制其余按 10 进制。2 进制转整型将二进制字符串转换为整型时需要显式指定base 2#include iostream #include string using namespace std; int main() { string s 1010; int num stoi(s, nullptr, 2); cout num endl; // 输出 10 return 0; }8 进制转整型将八进制字符串转换为整型时指定base 8#include iostream #include string using namespace std; int main() { string s 17; int num stoi(s, nullptr, 8); cout num endl; // 输出 15 return 0; }10 进制转整型十进制是最常用的场景默认base 10也可以省略第三个参数#include iostream #include string using namespace std; int main() { string s 123; int num stoi(s); cout num endl; // 输出 123 return 0; }16 进制转整型将十六进制字符串转换为整型时指定base 16#include iostream #include string using namespace std; int main() { string s 1A; int num stoi(s, nullptr, 16); cout num endl; // 输出 26 return 0; }注意事项当字符串无法转换为整型时stoi 会抛出invalid_argument异常当转换结果超出 int 范围时会抛出out_of_range异常。stoi 会跳过字符串开头的空白字符并从第一个有效字符开始解析。如果字符串包含非数字字符如 12abstoi 会解析到第一个非法字符为止剩余部分不会报错。
上一篇/下一篇内容由系统自动关联 返回资讯列表 →